Part Number Hot Search : 
0100S ONTROL DDZ24C 560KD14 SK12H60 0100S 450M2D 450M2D
Product Description
Full Text Search
 

To Download ATMEGA406-14 Datasheet File

  If you can't view the Datasheet, Please click here to try to view without PDF Reader .  
 
 


  Datasheet File OCR Text:
  features ? high performance, low power avr ? 8-bit microcontroller ? advanced risc architecture ? 124 powerful instructions - mo st single clock cycle execution ? 32 x 8 general purpose working registers ? fully static operation ? up to 1 mips throughput at 1 mhz ? nonvolatile program and data memories ? 40k bytes of in-system self-programma ble flash, endurance: 10,000 write/erase cycles ? optional boot code section with independent lock bits in-system programming by on-chip boot program true read-while-write operation ? 512 bytes eeprom, endurance: 100,000 writ e/erase cycles ? 2k bytes internal sram ? programming lock fo r software security ? on-chip debugging ? extensive on-chip debug support ? available through jtag interface ? battery management features ? two, three, or four cells in series ? deep under-voltage protection ? over-current protection (charge and discharge) ? short-circuit protection (discharge) ? integrated cell balancing fets ? high voltage outputs to drive charge/precharge/discharge fets ? peripheral features ? one 8-bit timer/counter with separate prescaler, compare mode, and pwm ? one 16-bit timer/counter with separate prescaler and compare mode ? 12-bit voltage adc, eight exte rnal and two internal adc inputs ? high resolution coulomb counte r adc for current measurements ? twi serial interface for sm-bus ? programmable wake-up timer ? programmable watchdog timer ? special microcontroller features ? power-on reset ? on-chip voltage regulator ? external and internal interrupt sources ? four sleep modes: idle, power-save, power-down, and power-off ? packages ? 48-pin lqfp ? operating voltage: 4.0 - 25v ? maximum withstand voltage (high-voltage pins): 28v ? temperature range: -30c to 85c ? speed grade: 1 mhz 8-bit microcontroller with 40k bytes in-system programmable flash atmega406 preliminary 2548f?avr?03/2013
2 2548f?avr?03/2013 atmega406 1. pin configurations figure 1-1. pinout atmega406. 1.1 disclaimer typical values contained in th is datasheet are based on simula tions and characterization of other avr microcontrollers manufactured on th e same process technology. min and max values will be available after the device is characterized. 1 2 3 4 5 6 7 8 9 10 11 12 36 35 34 33 32 31 30 29 28 27 26 25 sgnd (adc0 /pcint0 ) pa0 (adc1 /pcint1 ) pa1 (adc2 /pcint2 ) pa2 (adc3 /pcint3 ) pa3 vreg vcc gnd (adc4/int0 /pcint4 ) pa4 (int1 /pcint5 ) pa5 (int2 /pcint6 ) pa6 (int3/pcint7) pa7 pvt od vfet oc opc batt pc0 gnd pd1 pd0 (t0) pb7 (oc0b/pcint15) pb6 (oc0a/pcint14) 48 47 46 45 44 43 42 41 40 39 38 37 13 14 15 16 17 18 19 20 21 22 23 24 reset xtal1 xtal2 gnd (tdo/pcint8) pb0 (tdi/pcint9) pb1 (tms/pcint10) pb2 (tck/pcint11) pb3 (pcint12) pb4 (pcint13) pb5 scl sda nni ni pi ppi vrefgnd vref nv pv1 pv2 pv3 pv4 gnd top view
3 2548f?avr?03/2013 atmega406 2. overview the atmega406 is a low-power cmos 8-bit micr ocontroller based on the avr enhanced risc architecture. by executing powerful instruct ions in a single cl ock cycle, th e atmega406 achieves throughputs approaching 1 mips at 1 mhz. 2.1 block diagram figure 2-1. block diagram the atmega406 provides the following features: a voltage regulator, dedicated battery protec- tion circuitry, integrated cell balancing fets, high-voltage analog front-end, and an mcu with two adcs with on-chip voltage refe rence for battery fuel gauging. the voltage regulator operates at a wide range of voltages, 4.0 - 25 volts. this voltage is regu- lated to a constant supply voltage of nominally 3.3 volts for the integrated logic and analog functions. the battery protection monitors the battery voltage and charge/discharge current to detect illegal conditions and protect the battery from thes e when required. the illegal conditions are deep under-voltage during discharging, short-circuit du ring discharging and over-current during charg- ing and discharging. porta (8) twi sram flash cpu eeprom pv2 nv opc oc od fet control battery protection voltage adc voltage reference coulumb counter adc gnd vcc reset power supervision por & reset watchdog oscillator watchdog timer oscillator circuits / clock generation ppi nni pvt sgnd vref vrefgnd pi ni pa7..0 pa3..0 16 bit t/c1 8 bit t/c0 portb (8) pb7..0 jtag wake-up timer voltage regulator charger detect vfet vreg batt pv1 data b u s portc (1) pc0 sca scl cell balancing pv3 pv4 portd (2) pd1..0 xtal1 xtal2
4 2548f?avr?03/2013 atmega406 the integrated cell balancing fets allow ce ll balancing algorithms to be implemented in software. the mcu provides the following features: 40k bytes of in-system programmable flash with read-while-write capabilities, 512 bytes eeprom, 2k byte sram , 32 general purpose working registers, 18 general purpose i/o lines, 11 high-volt age i/o lines, a jtag interface for on-chip debugging support and programming, two flexible timer/counters with pwm and compare modes, one wake-up timer, an sm-bus compliant twi module, internal and external interrupts, a 12-bit sigma delta adc for voltage and temper ature measurements, a high resolution sigma delta adc for coulomb counting and instantaneous current measurements, a programmable watchdog timer with intern al oscillator, and four software selectable power saving modes. the avr core combines a rich instruction set wit h 32 general purpose working registers. all the 32 registers are directly connected to the arit hmetic logic unit (alu), allowing two independent registers to be accessed in one single instruction executed in one clock cycle. the resulting architecture is more code efficient while achiev ing throughputs up to ten times faster than con- ventional cisc microcontrollers. the idle mode stops the cpu while allowing the othe r chip function to continue functioning. the power-down mode allows the voltage regulator, battery protection, regulator current detection, watchdog timer, and wake-up timer to operate, wh ile disabling all other chip functions until the next interrupt or hardware reset. in power-save mode, the wake-up timer and coulomb coun- ter adc continues to run. the device is manufactured using atmel?s high voltage high density non-volatile memory tech- nology. the on-chip isp flash allows the program memory to be reprogrammed in-system, by a conventional non-volatile memory programmer or by an on-chip boot program running on the avr core. the boot program can use any interfac e to download the application program in the application flash memory. software in the boot flash section will continue to run while the application flash section is updated, providing true read-while-write operation. by combining an 8-bit risc cpu with in-system self-program mable flash, fuel gaug ing adcs, dedicated bat- tery protection circuitry, cell balancing fets, and a voltage regulator on a monolithic chip, the atmel atmega406 is a powerful microcontroller that provides a highly flexible and cost effective solution for li-ion smart battery applications. the atmega406 avr is supported with a full su ite of program and syst em development tools including: c compilers, macro assemblers, program debugger/simulators, and on-chip debugger.
5 2548f?avr?03/2013 atmega406 2.2 pin descriptions 2.2.1 vfet high voltage supply pin. this pin is used as suppl y for the internal voltage regulator, described in ?voltage regulator? on page 114 . in addition the voltage level on this pin is monitored by the bat- tery protection circuit, for deep-unde r-voltage protection. for details, see ?battery protection? on page 125 . 2.2.2 vcc digital supply voltage. no rmally connected to vreg. 2.2.3 vreg output from the internal voltage regulator. used for external decoupling to ensure stable regu- lator operation. for details, see ?voltage regulator? on page 114 . 2.2.4 vref internal voltage reference for exte rnal decoupling. for details, see ?voltage reference and temperature sensor? on page 121 . 2.2.5 vrefgnd ground for decoupling of internal voltage reference. for details, see ?voltage reference and temperature sensor? on page 121 . 2.2.6 gnd ground 2.2.7 sgnd signal ground pin, used as reference for voltage-adc conversions. for details, see ?voltage adc ? 10-channel general purpose 12 -bit sigma-delta adc? on page 116 . 2.2.8 port a (pa7:pa0) pa3:pa0 serves as the analog inpu ts to the voltage a/d converter. port a also serves as a low-voltage 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). as inputs, port a pins th at are externally pulled low will source current if the pull-up resistors are activated. the port a pi ns are tri-stated when a reset condition becomes active, even if the clock is not running. port a also serves the functions of various sp ecial features of the atmega406 as listed in ?alter- nate functions of port a? on page 68 . 2.2.9 port b (pb7:pb0) port b is a low-voltage 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). as inputs, port b pins that are exter nally pulled low will source current if the pull-up resistors are activated. the port b pins are tri-stated when a reset condition becomes active, even if the clock is not running. port b also serves the functions of various sp ecial features of the atmega406 as listed in ?alter- nate functions of port b? on page 70 .
6 2548f?avr?03/2013 atmega406 2.2.10 port c (pc0) port c is a high voltage open drain output port. 2.2.11 port d (pd1:pd0) port d is a low-voltage 2-bit bi-directional i/o por t with internal pull-up resistors (selected for each bit). as inputs, port d pins that are exter nally pulled low will source current if the pull-up resistors are activated. the port d pins are tri-stated when a reset condition becomes active, even if the clock is not running. port d also serves the functions of various s pecial features of the atmega406 as listed in ?alter- nate functions of port d? on page 72 . 2.2.12 scl smbus clock, open drain bidirectional pin. 2.2.13 sda smbus data, open drain bidirectional pin. 2.2.14 oc/od/opc high voltage output to drive external charge /discharge/pre-charge fets. for details, see ?fet control? on page 133 . 2.2.15 ppi/nni unfiltered positive/negative input from external current sense resistor, used by the battery pro- tection circuit, for over-current and short-circuit detection. for details, see ?battery protection? on page 125 . 2.2.16 pi/ni filtered positive/negative input from external cu rrent sense resistor, used to by the coulomb counter adc to measure charge/discharge currents flowing in the battery pack. for details, see ?coulomb counter - dedicated fuel gauging sigma-delta adc? on page 106 . 2.2.17 nv/pv1/pv2/pv3/pv4 nv, pv1, pv2, pv3, and pv4 are th e inputs for battery cells 1, 2, 3 and 4, used by the voltage adc to measure each cell voltage. for details, see ?voltage adc ? 10-channel general pur- pose 12-bit sigma-delta adc? on page 116 . 2.2.18 pvt pvt defines the pull-up level for the od output. 2.2.19 batt input for detecting when a charger is connected. this pin also defines the pull-up level for oc and opc outputs. 2.2.20 reset reset input. a low level on this pin for longer than the minimum pulse length will generate a reset, even if the clock is not running. the minimum pulse length is given in table 11 on page 38. shorter pulses are not guaranteed to generate a reset.
7 2548f?avr?03/2013 atmega406 2.2.21 xtal1 input to the invertin g oscillator amplifier. 2.2.22 xtal2 output from the invert ing oscillator amplifier. 3. resources a comprehensive set of development tools, appl ication notes and datashee ts are available for download on http:// www.atmel.com/avr. 4. about code examples this documentation contains simple code examples that briefly show how to use various parts of the device. these code examples assume that the part specific header file is included before compilation. be aware that not all c compiler vendors include bit definitions in the header files and interrupt handling in c is compiler dependent. please confirm with the c compiler documen- tation for more details. for i/o registers located in extended i/o map, ?in?, ?out?, ?sbis?, ?sbic?, ?cbi?, and ?sbi? instructions must be replaced with instructio ns that allow access to extended i/o. typically ?lds? and ?sts? combined with ? sbrs?, ?sbrc?, ? sbr?, and ?cbr?.
8 2548f?avr?03/2013 atmega406 5. avr cpu core 5.1 introduction this section discusses the avr core architecture in general. the main function of the cpu core is to ensure correct program execution. the cpu must therefore be able to access memories, perform calculations, control peri pherals, and handle interrupts. 5.2 architectural overview figure 5-1. block diagram of the avr architecture in order to maximize performance and parallelism, the avr uses a harvard architecture ? with separate memories and buses for program and data. instructions in the program memory are executed with a single level pipe lining. while one instruction is being executed, the next instruc- tion is pre-fetched from the program memory. this concept enables instructions to be executed in every clock cycle. the program memory is in-system reprogrammable flash memory. flash program memory instruction register instruction decoder program counter control lines 32 x 8 general purpose registrers alu status and control i/o lines eeprom data bus 8-bit data sram direct addressing indirect addressing interrupt unit watchdog timer i/o module 2 i/o module1 i/o module n
9 2548f?avr?03/2013 atmega406 the fast-access register file contains 32 x 8-bit general purpose working registers with a single clock cycle access time. this allows single-cycle ar ithmetic logic unit (alu ) operation. in a typ- ical alu operation, two operands are output from the register file, the operation is executed, and the result is stored back in the register file ? in one clock cycle. six of the 32 registers can be used as three 16 -bit indirect address register pointers for data space addressing ? enabling efficient address calculations. one of the these address pointers can also be used as an address pointer for look up tables in flash program memory. these added function registers are the 16-bit x-, y-, and z-register, described later in this section. the alu supports arithmetic and logic operations between registers or between a constant and a register. single register operations can also be executed in the alu. after an arithmetic opera- tion, the status register is up dated to reflect information about the result of the operation. program flow is provided by conditional and uncon ditional jump and call instructions, able to directly address the whole addres s space. most avr instructions have a single 16-bit word for- mat. every program memory address co ntains a 16- or 32-bit instruction. program flash memory space is divided in tw o sections, the boot program section and the application program section. both sections have dedicated loc k bits for write and read/write protection. the spm instruction that writes into the application flash memory section must reside in the boot program section. during interrupts and subroutine calls, the return address program counter (pc) is stored on the stack. the stack is effectively allocated in th e general data sram, and consequently the stack size is only limited by the total sram size an d the usage of the sram. all user programs must initialize the sp in the reset routine (before subroutines or interrupts are executed). the stack pointer (sp) is read/write accessible in the i/o space. the data sram can easily be accessed through the five different addressing mo des supported in the avr architecture. the memory spaces in the avr architecture are all linear and regular memory maps. a flexible interrupt module has its control r egisters in the i/o spac e with an additional global interrupt enable bit in the status register. all interrupts have a s eparate interrupt vector in the interrupt vector table. the interrupts have priority in accordance with their interrupt vector posi- tion. the lower the interr upt vector address, the higher the priority. the i/o memory space contains 64 addresses for cpu peripheral functi ons as control regis- ters, spi, and other i/o functions. the i/o memory can be accessed directly, or as the data space locations following those of the register file, 0x20 - 0x 5f. in addition, the atmega406 has extended i/o space from 0x60 - 0xff in sram where only the st/sts/std and ld/lds/ldd instructions can be used. 5.3 alu ? arithm etic logic unit the high-performance avr alu operates in dire ct connection with all the 32 general purpose working registers. within a single clock cycle, arithmetic operations between general purpose registers or between a register and an immedi ate are executed. the alu operations are divided into three main categories ? arithmetic, logical, and bit-functions. some implementations of the architecture also provide a powerful multip lier supporting both signed/unsigned multiplication and fractional format. see the ?instruction set? section for a detailed description.
10 2548f?avr?03/2013 atmega406 5.4 status register the status register contains information about th e result of the most recently executed arithme- tic instruction. this information can be used for altering program flow in order to perform conditional operations. note that the status re gister is updated after all alu operations, as specified in the ?avr instructio n set? description. this will in many cases remove the need for using the dedicated compare instructions, resu lting in faster and more compact code. the status register is not automatically st ored when entering an interrupt routine and restored when returning from an interrupt. this must be handled by software. 5.4.1 sreg ? avr status register the avr status register ? sreg ? is defined as: ? bit 7 ? i: global interrupt enable the global interrupt enable bit must be set for th e interrupts to be enabled. the individual inter- rupt enable control is then performed in separate control registers. if the global interrupt enable register is cleared, none of t he interrupts are enabled independent of the individual interrupt enable settings. the i-bit is cleared by hardware after an interrupt has occurred, and is set by the reti instruction to enable subsequent interr upts. the i-bit can also be set and cleared by the application with the sei and cli instructions, as described in the ?avr instruction set? description. ? bit 6 ? t: bit copy storage the bit copy instructions bld (bit load) and bst (b it store) use the t-bi t as source or desti- nation for the operated bit. a bit from a register in the register file can be copied into t by the bst instruction, and a bit in t can be copied into a bit in a register in the register file by the bld instruction. ? bit 5 ? h: half carry flag the half carry flag h indicates a half carry in so me arithmetic operations. half carry is useful in bcd arithmetic. see the ?avr instruction set? for detailed information. ? bit 4 ? s: sign bit, s = n ?? v the s-bit is always an exclusive or between the negative flag n and the two?s complement overflow flag v. see the ?avr inst ruction set? for de tailed information. ? bit 3 ? v: two?s complement overflow flag the two?s complement overflow flag v supports two?s complement arithmetics. see the ?avr instruction set? for detailed information. ? bit 2 ? n: negative flag the negative flag n indicates a negative result in an arithmetic or logic operation. see the ?avr instruction set? for detailed information. bit 76543210 0x3f (0x5f) i t h s v n z c sreg read/write r/w r/w r/ wr/wr/wr/wr/wr/w initial value 0 0 0 0 0 0 0 0
11 2548f?avr?03/2013 atmega406 ? bit 1 ? z: zero flag the zero flag z indicates a zero result in an ar ithmetic or logic operation. see the ?avr instruc- tion set? for detailed information. ? bit 0 ? c: carry flag the carry flag c indicates a carry in an arithmet ic or logic operation. see the ?avr instruction set? for detailed information. 5.5 general purpose register file the register file is optimized for the avr enhanc ed risc instruction set. in order to achieve the required performance and flex ibility, the following in put/output schemes ar e supported by the register file: ? one 8-bit output operand and one 8-bit result input ? two 8-bit output operands and one 8-bit result input ? two 8-bit output operands and one 16-bit result input ? one 16-bit output operand and one 16-bit result input figure 5-2 shows the structure of the 32 genera l purpose working registers in the cpu. figure 5-2. avr cpu general purpose working registers most of the instructions operating on the register file have direct access to all registers, and most of them are single cycle instructions. as shown in figure 5-2 , each register is also assigned a data memory address, mapping them directly into the first 32 loca tions of the user data space. although not being physically imple- mented as sram locations, this memory organizati on provides great flexibility in access of the registers, as the x-, y- and z-pointer registers can be set to index any register in the file. 7 0 addr. r0 0x00 r1 0x01 r2 0x02 ? r13 0x0d general r14 0x0e purpose r15 0x0f working r16 0x10 registers r17 0x11 ? r26 0x1a x-register low byte r27 0x1b x-register high byte r28 0x1c y-register low byte r29 0x1d y-register high byte r30 0x1e z-register low byte r31 0x1f z-register high byte
12 2548f?avr?03/2013 atmega406 5.5.1 the x-register, y-register, and z-register the registers r26:r31 have some added functions to their general purpose usage. these regis- ters are 16-bit address pointers for indirect addressing of the data space. the three indirect address registers x, y, and z are defined as described in figure 5-3 . figure 5-3. the x-, y-, and z-registers in the different addressing modes these address registers have functions as fixed displacement, automatic increment, and automatic decrement (s ee the ?avr instruction set? description for details). 5.6 stack pointer the stack is mainly used for storing temporary data, for storing local variables and for storing return addresses after interrupts and subroutine calls. the stack pointer register always points to the top of the stack. note that the stack is implemented as growing from higher memory loca- tions to lower memory location s. this implies that a stack push command decreases the stack pointer. the stack pointer points to the data sram stack area where the subroutine and interrupt stacks are located. this stack space in the da ta sram must be defined by the program before any subroutine calls are executed or interrupt s are enabled. the stack pointer must be set to point above 0x100. the stack pointer is decremented by one when data is pushed onto the stack with the push instruction, and it is decremented by two when the return address is pushed onto the stack with subroutine call or in terrupt. the stack pointer is incremented by one when data is popped from the stack with the pop instruction, and it is incremented by two when data is popped from the stack with return from subroutine ret or return from interrupt reti. the avr stack pointer is implemented as two 8- bit registers in the i/o space. the number of bits actually used is implementation dependent. no te that the data space in some implementa- tions of the avr architecture is so small that only spl is needed. in this case, the sph register will not be present. 15 xh xl 0 x-register 7 0 7 0 r27 (0x1b) r26 (0x1a) 15 yh yl 0 y-register 7 0 7 0 r29 (0x1d) r28 (0x1c) 15 zh zl 0 z-register 7 0 7 0 r31 (0x1f) r30 (0x1e)
13 2548f?avr?03/2013 atmega406 5.6.1 sph and spl ? stack pointer register 5.7 instruction execution timing this section describes the general access timing concepts for instructi on execution. the avr cpu is driven by the cpu clock clk cpu , directly generated from the selected clock source for the chip. no internal clo ck division is used. figure 5-4 shows the parallel instruction fetches and instruction executions enabled by the har- vard architecture and the fast-acc ess register file concept. this is the basic pipelining concept to obtain up to 1 mips per mhz with the corr esponding unique results for functions per cost, functions per clocks, and functions per power-unit. figure 5-4. the parallel instruction fetche s and instruction executions figure 5-5 shows the internal timing concept for the register file. in a single clock cycle an alu operation using two register operands is executed, and the result is stored back to the destina- tion register. figure 5-5. single cycle alu operation bit 151413121110 9 8 0x3e (0x5e) sp15 sp14 sp13 sp12 sp11 sp10 sp9 sp8 sph 0x3d (0x5d) sp7 sp6 sp5 sp4 sp3 sp2 sp1 sp0 spl 76543210 read/write r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w initial value 00000000 00000000 clk 1st instruction fetch 1st instruction execute 2nd instruction fetch 2nd instruction execute 3rd instruction fetch 3rd instruction execute 4th instruction fetch t1 t2 t3 t4 cpu total execution time register operands fetch alu operation execute result write back t1 t2 t3 t4 clk cpu
14 2548f?avr?03/2013 atmega406 5.8 reset and in terrupt handling the avr provides several different interrupt sources. these interrupts and the separate reset vector each have a separate program vector in the program memory space. all interrupts are assigned individual enable bits which must be writ ten logic one together with the global interrupt enable bit in the status register in orde r to enable the interrupt. depending on the program counter value, interrupts may be automatically disabled when boot lock bits blb02 or blb12 are programmed. this feature improves software security . see the section ?memory program- ming? on page 195 for details. the lowest addresses in the program memory space are by default defined as the reset and interrupt vectors. the complete list of vectors is shown in ?interrupts? on page 51 . the list also determines the priority levels of the different interrupts. the lower the address the higher is the priority level. reset has the highest priority. the interrupt vectors can be moved to the start of the boot flash section by setting the ivsel bit in the mcu control register (mcucr). refer to ?interrupts? on page 51 for more information. the reset vector can also be moved to the start of the boot flash section by prog ramming the bootrst fuse, see ?boot loader support ? read- while-write self-programming? on page 178 . when an interrupt occurs, the global interrupt enable i-bit is cleared and all interrupts are dis- abled. the user software can write logic one to the i-bit to enable nested interrupts. all enabled interrupts can then interrupt the current interrupt routine. the i-bit is automatically set when a return from interrupt instru ction ? reti ? is executed. there are basically two types of interrupts. the fi rst type is triggered by an event that sets the interrupt flag. for these interrup ts, the program counter is vector ed to the actual interrupt vector in order to execute the interrupt handling rout ine, and hardware clears the corresponding inter- rupt flag. interrupt flags can also be cleared by wr iting a logic one to the flag bit position(s) to be cleared. if an interrupt condition occurs while the corresponding interrupt enable bit is cleared, the interrupt flag will be set and re membered until the inte rrupt is enabled, or the flag is cleared by software. similarly, if one or more interrupt condit ions occur while the global interrupt enable bit is cleared, the corresponding interrupt flag(s) w ill be set and remembered until the global interrupt enable bit is set, and will th en be executed by order of priority. the second type of interrupts will trigger as long as the interrupt condition is present. these interrupts do not necessarily have interrupt flags. if the interrupt condition disappears before the interrupt is enabled, the in terrupt will not be triggered. when the avr exits from an inte rrupt, it will always retu rn to the main pr ogram and execute one more instruction before any pending interrupt is served. note that the status register is not automatically stored when entering an interrupt routine, nor restored when returning from an interrupt routine. this must be handled by software. when using the cli instruction to disable interrupts, the interrup ts will be immediately disabled. no interrupt will be ex ecuted after the cli instru ction, even if it occurs simultaneously with the
15 2548f?avr?03/2013 atmega406 cli instruction. the following example shows how th is can be used to avoid interrupts during the timed eeprom write sequence. when using the sei instruction to enable interr upts, the instruction following sei will be exe- cuted before any pending interrupts, as shown in this example. 5.8.1 interrupt response time the interrupt execution response for all the enabled avr interrupts is four clock cycles mini- mum. after four clock cycles the program vector address for the actual interrupt handling routine is executed. during this four clock cycle perio d, the program counter is pushed onto the stack. the vector is normally a jump to the interrupt routine, and this jump takes three clock cycles. if an interrupt occurs during execution of a multi- cycle instruction, this in struction is completed before the interrupt is served. if an interrupt occurs when the mcu is in sleep mode, the interrupt execution response time is increased by four clo ck cycles. this increase co mes in addition to the start-up time from the selected sleep mode. a return from an interrupt handling routine take s four clock cycles. during these four clock cycles, the program counter (two bytes) is po pped back from the stack, the stack pointer is incremented by two, and the i-bit in sreg is set. assembly code example in r16, sreg ; store sreg value cli ; disable interrupts during timed sequence sbi eecr, eemwe ; start eeprom write sbi eecr, eewe out sreg, r16 ; restore sreg value (i-bit) c code example char csreg; csreg = sreg; /* store sreg value */ /* disable interrupts during timed sequence */ _cli(); eecr |= (1< 16 2548f?avr?03/2013 atmega406 6. avr memories this section describes the different memories in the atmega406. the avr architecture has two main memory spaces, the data memory and t he program memory space. in addition, the atmega406 featur es an eeprom memory for data storage. all three memory sp aces are linear and regular. 6.1 in-system reprogrammabl e flash program memory the atmega406 contains 40k bytes on-chip in-system reprogrammable flash memory for program storage. since all avr instructions are 16 or 32 bits wide, the flash is organized as 20k x 16. for software security, the flash progr am memory space is divided into two sections, boot program section and application program section. the flash memory has an endurance of at leas t 10,000 write/erase cycles. the atmega406 program counter (pc) is 15 bits wide, thus addressing the 20k program memory locations. the operation of boot program section and associat ed boot lock bits for software protection are described in detail in ?boot loader support ? read-while-write self-programming? on page 178 . ?memory programming? on page 195 contains a detailed description on flash data serial downloading. constant tables can be allocated within the entire program memory address space (see the lpm ? load program memory instruction description). timing diagrams for instruction fetc h and execution are presented in ?instruction execution tim- ing? on page 13 . figure 6-1. program memory map 0x0000 0x4fff program memory application flash section boot flash section
17 2548f?avr?03/2013 atmega406 6.2 sram data memory figure 6-2 shows how the atmega406 sram memory is organized. the atmega406 is a complex microcontroller with more peripheral units than can be supported within the 64 locations reserved in the opco de for the in and out instructions. for the extended i/o space from 0x60 - 0xff in sram, only the st/sts/std and ld/lds/ldd instruc- tions can be used. the lower 2,304 data memory locations address both the register file, the i/o memory, extended i/o memory, and the internal data sr am. the first 32 locati ons address the register file, the next 64 location the standard i/o memory, then 160 locations of extended i/o memory, and the next 2,048 locations address the internal data sram. the five different addressing modes for the data memory cover: direct, indirect with displace- ment, indirect, indirect with pre-decrement, and indirect with post-increment. in the register file, registers r26 to r31 feature the indirect addressing pointer registers. the direct addressing reaches the entire data space. the indirect with displacement mode reaches 63 address locations from the base address given by the y- or z-register. when using register indirect addressing modes with automatic pre-decrement and post-incre- ment, the address registers x, y, and z are decremented or incremented. the 32 general purpose working registers, 64 i /o registers, 160 extended i/o registers, and the 2,048 bytes of internal data sram in the atmega406 are all accessible through all these addressing modes. the register file is described in ?general purpose register file? on page 11 . figure 6-2. data memory map 32 registers 64 i/o registers internal sram (2048 x 8) 0x0000 - 0x001f 0x0020 - 0x005f 0x08ff 0x0060 - 0x00ff data memory 160 ext i/o reg. 0x0100
18 2548f?avr?03/2013 atmega406 6.2.1 data memory access times this section describes the general access timi ng concepts for internal memory access. the internal data sram access is performed in two clk cpu cycles as described in figure 6-3 . figure 6-3. on-chip data sram access cycles 6.3 eeprom data memory the atmega406 contains 512 by tes of data eeprom memory. it is organized as a separate data space, in which single by tes can be read and wr itten. the eeprom has an endurance of at least 100,000 write/erase cycles. the access between the eeprom and the cpu is described in the following, specif ying the eeprom address registers, the eeprom data register, and the eeprom control register. for a detailed description of serial and pa rallel data download ing to the eeprom, see page 211 and page 199 respectively. 6.3.1 eeprom read/write access the eeprom access registers are accessible in the i/o space. the write access time for the eeprom is given in table 6-1 . a self-timing function, however, lets the user software detect when the next byte can be written. if the user code contains instruc- tions that write the eeprom, some precautions mu st be taken. in order to prevent unintentional eeprom writes, a specific write procedure must be followed. refer to the description of the eeprom control regist er for details on this. when the eeprom is read, the cpu is halted for fo ur clock cycles before the next in struction is executed. when the eeprom is written, the cpu is halte d for two clock cycles before the next instruction is executed. clk wr rd data data address address valid t1 t2 t3 compute address read write cpu memory access instruction next instruction
19 2548f?avr?03/2013 atmega406 6.3.2 eearh and eearl ? th e eeprom address register ? bits 15:9 ? res: reserved bits these bits are reserved bits in the atmega406 and will always read as zero. ? bits 8:0 ? eear8:0: eeprom address the eeprom address registers ? eearh and eearl specify the eeprom address in the 512 bytes eeprom space. the eeprom data bytes are ad dressed linearly between 0 and 511. the initial value of eear is undefined. a proper value must be written before the eeprom may be accessed. 6.3.3 eedr ? the eeprom data register ? bits 7:0 ? eedr7:0: eeprom data for the eeprom write operation, the eedr register contains the data to be written to the eeprom in the address given by the eear regi ster. for the eeprom read operation, the eedr contains the data read out from the eeprom at the add ress given by eear. 6.3.4 eecr ? the eeprom control register ? bits 7:6 ? res: reserved bits these bits are reserved bits in the atmega406 and will always read as zero. ? bits 5:4 ? eepm1 and eepm0: eeprom programming mode bits the eeprom programming mode bit setting defines which prog ramming action th at will be trig- gered when writing eepe. it is pos sible to program data in one at omic operation (erase the old value and program the new value) or to split the erase and write operations in two different operations. the programming times for the different modes are shown in table 6-1 . while eepe is set, any write to eepmn will be ignored. du ring reset, the eepmn bits will be reset to 0b00 unless the eeprom is busy programming. bit 151413121110 9 8 0x22 (0x42) ? ? ? ? ? ? ? eear8 eearh 0x21 (0x41) eear7 eear6 eear5 eear4 eear3 eear2 eear1 eear0 eearl 76543210 read/write rrrrrrrr/w r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 x xxxxxxxx bit 76543210 0x20 (0x40) msb lsb eedr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 765432 10 0x1f (0x3f) ? ? eepm1 eepm0 eerie eempe eepe eere eecr read/write r r r/w r/w r/w r/w r/w r/w initial value 0 0 x x 0 0 x 0
20 2548f?avr?03/2013 atmega406 ? bit 3 ? eerie: eeprom ready interrupt enable writing eerie to one enables the eeprom ready interrupt if the i bit in sreg is set. writing eerie to zero disables the interrupt. the eepro m ready interrupt generates a constant inter- rupt when eepe is cleared. ? bit 2 ? eempe: eeprom master programming enable the eempe bit determines whether setting eepe to one causes the eeprom to be written. when eempe is set, setting eepe within four cloc k cycles will write data to the eeprom at the selected address if eempe is zero, setting eepe will have no effect. when eempe has been written to one by software, ha rdware clears the bit to zero after four clock cycles. see the description of the eepe bit fo r an eeprom write procedure. ? bit 1 ? eepe: eeprom programming enable the eeprom write enable signal eepe is the wr ite strobe to the eeprom. when address and data are correctly set up, the eepe bit must be written to one to write the value into the eeprom. the eempe bit must be wr itten to one be fore a logical one is written to eepe, other- wise no eeprom write takes pl ace. the following pr ocedure should be followed when writing the eeprom (the order of steps 3 and 4 is not essential): 1. wait until eepe becomes zero. 2. wait until selfprgen in spmcsr becomes zero. 3. write new eeprom addres s to eear (optional). 4. write new eeprom data to eedr (optional). 5. write a logical one to the eempe bit while writing a zero to eepe in eecr. 6. within four clock cycles after sett ing eempe, write a logical one to eepe. the eeprom can not be programmed during a cpu write to the flash memory. the software must check that the flash programming is co mpleted before initiating a new eeprom write. step 2 is only relevant if the software contai ns a boot loader allowing the cpu to program the flash. if the flash is never being updated by the cpu, step 2 can be omitted. see ?boot loader support ? read-while-write self-programming? on page 178 for details about boot programming. caution: an interrupt between step 5 and step 6 will make the write cycle fail, since the eeprom master write enable will time-out. if an interrupt routine accessing the eeprom is interrupting another eeprom acce ss, the eear or eedr register will be modified, causing the interrupted eeprom access to fail. it is recommended to have the global interrupt flag cleared during all the steps to avoid these problems. table 6-1. eeprom mode bits eepm1 eepm0 programming time operation 0 0 3.4 ms erase and write in one operation (atomic operation) 0 1 1.8 ms erase only 1 0 1.8 ms write only 1 1 ? reserved for future use
21 2548f?avr?03/2013 atmega406 when the write access time has elapsed, the eepe bit is cleared by hardware. the user soft- ware can poll this bit and wait for a zero befo re writing the next byte. when eepe has been set, the cpu is halted for two cycles before the next instruction is executed. ? bit 0 ? eere: eeprom read enable the eeprom read enable signal eere is the re ad strobe to the eeprom. when the correct address is set up in the eear regi ster, the eere bit must be written to a logic one to trigger the eeprom read. the eeprom read access takes one instruction, and the requ ested data is available immediately. when t he eeprom is read, the cpu is ha lted for four cycles before the next instruction is executed. the user should poll the eepe bit before starting the read operation. if a write operation is in progress, it is neither possi ble to read the e eprom, nor to change the eear register. the calibrated oscillator is used to time the eeprom accesses. table 6-2 lists the typical pro- gramming time for eeprom access from the cpu. the following code examples show one assembly and one c function for writing to the eeprom. the examples assume that interrupts are controlled (e.g. by dis abling interrupts glob- ally) so that no interrupts will occur during ex ecution of these functions. the examples also assume that no flash boot loader is present in the software. if such code is present, the eeprom write function must also wait for any on going spm command to finish. table 6-2. eeprom programming time symbol number of calibrated rc os cillator cycles typ programming time eeprom write (from cpu) 26,368 3.3 ms
22 2548f?avr?03/2013 atmega406 the next code examples show assembly and c functions for reading the eeprom. the exam- ples assume that interrupts are controlled so that no interrupts will occur during execution of these functions. assembly code example eeprom_write: ; wait for completion of previous write sbic eecr,eewe rjmp eeprom_write ; set up address (r18:r17) in address register out eearh, r18 out eearl, r17 ; write data (r16) to data register out eedr,r16 ; write logical one to eemwe sbi eecr,eemwe ; start eeprom write by setting eewe sbi eecr,eewe ret c code example void eeprom_write( unsigned int uiaddress, unsigned char ucdata) { /* wait for completion of previous write */ while(eecr & (1< 23 2548f?avr?03/2013 atmega406 assembly code example eeprom_read: ; wait for completion of previous write sbic eecr,eewe rjmp eeprom_read ; set up address (r18:r17) in address register out eearh, r18 out eearl, r17 ; start eeprom read by writing eere sbi eecr,eere ; read data from data register in r16,eedr ret c code example unsigned char eeprom_read( unsigned int uiaddress) { /* wait for completion of previous write */ while(eecr & (1< 24 2548f?avr?03/2013 atmega406 6.4 i/o memory the i/o space definition of the atmega406 is shown in ?register summary? on page 236 . all atmega406 i/os and peripherals are placed in the i/o space. all i/o locations may be accessed by the ld/lds/ldd and st/sts/std instructions, transferring data between the 32 general purpose working registers and the i/o space. i/o registers wi thin the address range 0x00 - 0x1f are directly bit-acce ssible using the sbi and cbi instru ctions. in these registers, the value of single bits can be checked by using the sbis and sbic instructions. refer to the instruction set section for more details. when us ing the i/o specific commands in and out, the i/o addresses 0x00 - 0x3f must be used. when addr essing i/o registers as data space using ld and st instructions, 0x20 must be added to these addresses. the atmega406 is a complex microcontroller with more peripheral units than ca n be supported within the 64 location reserved in opcode for the in and out instructions. for the extended i/o space from 0x60 - 0xff in sram, only the st/sts/std and ld/lds/ldd instructions can be used. for compatibility with future devices, reserved bits should be written to zero if accessed. reserved i/o memory addresses should never be written. some of the status flags are clear ed by writing a logical one to th em. note that, unlike most other avrs, the cbi and sbi instructions will only oper ate on the specified bit, and can therefore be used on registers containing such status flags. the cbi and sbi instructions work with registers 0x00 to 0x1f only. the i/o and peripherals control regist ers are explained in later sections. 6.4.1 general purpose i/o registers the atmega406 contains three general purpose i/o registers. these registers can be used for storing any information, and they are particularly useful for st oring global variables and status flags. general purpose i/o regist ers within the address range 0x00 - 0x1f are directly bit- accessible using the sbi, cbi, sbis, and sbic instructions. 6.4.2 gpior2 ? general purpose i/o register 2 6.4.3 gpior1 ? general purpose i/o register 1 6.4.4 gpior0 ? general purpose i/o register 0 bit 76543210 0x2b (0x4b) msb lsb gpior2 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 0x2a (0x4a) msb lsb gpior1 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 0x1e (0x3e) msb lsb gpior0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
25 2548f?avr?03/2013 atmega406 7. system clock and clock options 7.1 clock systems and their distribution figure 7-1 presents the principal clock systems in the avr and their distribution. all of the clocks need not be active at a given time. in order to reduce power consumption, the clocks to modules not being used can be halted by using different sleep modes, as described in ?power manage- ment and sleep modes? on page 31 . the clock systems are detailed below. figure 7-1. clock distribution 7.1.1 cpu clock ? clk cpu the cpu clock is routed to parts of the syst em concerned with operat ion of the avr core. examples of such modules are the general pur pose register file, the status register and the data memory holding the stack po inter. halting the cpu clock inhi bits the core from performing general operations and calculations. 7.1.2 twi clock - clk twi the twi module is provided with a dedicated clock domain. this is because the twi module requires a 4 mhz clock to achiev e the specified data transfer speed. it also allows power reduction by halting the clk twi clock when twi communication is not used. note that address match detection in the tw i module is carried out asynchronously when clk twi is halted, enabling twi address watch detection in all sleep modes except power-off. 7.1.3 i/o clock ? clk i/o the i/o clock is used by the majority of the i/o modules. the i/o clock is also used by the exter- nal interrupt module, but note that some external interrupts are detected by asynchronous logic, allowing such interrupts to be detected even if the i/o clock is halted. 7.1.4 flash clock ? clk flash the flash clock controls operation of the flash interface. the flash clock is usually active simul- taneously with the cpu clock. ultra low power rc oscillator watchdog timer battery protection & fet control reset logic cpu core ram flash and eeprom voltage adc other i/o modules coulomb counter adc wake-up timer 1/4 avr clock control avr clock control slow rc oscillator fast rc oscillator clk cpu clk flash clk vadc clk i/o clk ccadc clk wut avr clock control twi 1/4 sync delay clk twi 32 khz crystal oscillator run-time selection clock multiplexer 1 0 twi disconnect delay
26 2548f?avr?03/2013 atmega406 7.1.5 voltage adc clock ? clk vadc the voltage adc is provided with a dedicated clock domain. this allows halting the cpu and i/o clocks in order to reduce noise generated by digital circuitry. this gives more accurate adc conversion results. 7.1.6 coulomb counter adc clock - clk ccadc the coulomb counter adc is provided with a dedic ated clock domain. this allows operating the coulomb counter adc in low power modes like power-save for continuous current measurements. 7.1.7 watchdog timer and battery protection clock the watchdog timer and battery protection are provided with a dedicated clock domain. this allows operation in all modes exce pt power-off. it also allows ve ry low power operation by utiliz- ing an ultra low power rc oscilla tor dedicated to this purpose. 7.2 clock sources the device has the following clock sources. the clocks are input to the avr clock generator, and routed to the appropriate modules. 7.3 calibrated fast rc oscillator the calibrated fast rc oscillator by default provides a 4.0 mhz cl ock, which is divided down to 1.0 mhz to all modules except the tw i. the frequency is nominal value at 25 ? c. this clock will operate with no external components. during reset, hardware loads the calibration byte into the fosccal register and thereby automatically calibrates the fast rc oscillator. at 25 ? c, this calibration gives a frequency of 4 mhz 3%. the oscillator can be calibrated to any frequency in the range 3.7 - 4.0 mhz within 1% accuracy, by changing the fosccal register. for more information on the pre-programmed calibration value, see the section ?calibration bytes? on page 198 . the start-up times for the fast rc oscillator are determined by the sut fuses as shown in table 7-1 on page 26 . note: 1. the device is shipped with this option selected. table 7-1. start-up times for the internal calib rated rc oscillator clock selection sut1:0 start-up time from power-down and power-save additional delay from reset 00 6 ck 14ck 01 6 ck 14ck + 4.1 ms 10 6 ck 14ck + 65 ms (1) 11 reserved
27 2548f?avr?03/2013 atmega406 7.4 32 khz cryst al oscillator xtal1 and xtal2 are input and output, respectively, of an inverting amplifier which can be con- figured for use as an on-chip oscillator, as shown in figure 7-2 . this oscillator is optimized for use with a 32.768 khz watch crystal. c1 and c2 should always be equal. the optimal value of the capacitors depends on the crystal or resonator in use, the amount of stray capaci tance, and the electromagn etic noise of the envi- ronment. for information on how to choose capacitors and othe r details on osc illator operation, refer to the 32 khz crystal oscillator application note. figure 7-2. 32 khz crystal osc illator connections 7.5 slow rc oscillator the slow rc oscillator provides a fixed 131 khz clock. this clock source can be used as a backup clock source in case of 32 khz crystal oscillator failure. it can also be used as the only run-time clock source in systems where the resu lting clock accuracy is acceptable. to provide good accuracy when used as a run-time clock so urce, the slow rc oscillator has a calibration byte stored in the signature address space. see the section ?calibration bytes? on page 198 . in order to get the actual timeout periods, the applic ation software must use this calibration byte to scale the wut time-outs found in table 10-1 on page 50 . 7.6 ultra low power rc oscillator the ultra low power rc oscillator (ulp oscillator ) provides a clock of 128 khz. it operates at very low power consumption, at th e expense of frequency accuracy. 7.7 cpu, i/o, flash, and voltage adc clock the clock source for the cpu, i/o, flash, and voltage adc is the calibra ted fast rc oscillator. note that the calibrated fast rc oscillator will provide a 4 mhz cl ock to the twi module and a 1 mhz clock to all other modules. when the cpu wakes up from power-down or po wer-save, the cpu clock source is used to time the start-up, ensuring a stable clock before instruction execution starts. when the cpu starts from reset, there is an additional delay allowing the voltage regulator to reach a stable level before commencing normal operation. the ult ra low power rc oscillator is used for tim- ing this real-time part of the start-up time. start-up times are determined by the sut fuses as xtal2 xtal1 gnd c2 c1
28 2548f?avr?03/2013 atmega406 shown in table 7-2 . the number of ultra low power rc osc illator cycles used for each time-out is shown in table 7-3 . 7.8 coulomb counter adc and wake-up timer clock the coulomb counter adc and wake-up timer cl ock operates asynchronously with the cpu clock, to allow low power operation in sleep modes. the clock source is either the 32 khz crystal oscillator, or the slow rc oscillator (divided by 4). the sele cted clock is input to the avr clock control unit, and is routed to the appropriate modules. the clock source for the coulomb counter adc and wake-up timer is selected by an i/o bit in the clock control and status register, see ?run-time clock source select? on page 28 for details. 7.9 watchdog timer and ba ttery protection clock the clock source for the watchdog timer and battery protection is the ultra low power rc oscillator. the oscillator is automatically enabled in all operat ional modes where either the watchdog timer, the battery protec tion, or both, are enabled. it is also enabled during reset. 7.10 run-time clock source select the clock source for the coulomb counter adc and wake-up timer is run-time selectable as either the 32 khz crystal oscillator, or the slow rc oscillator (div ided by 4). the clock source is selected by an i/o bit in the clock control and status register. the 32 khz crystal oscillator is the recommended clock source in order to achieve the highest clock accuracy. the slow rc oscillator is provided as a clock source for low cost systems, or as an alternate clock source in case of crystal cloc k failure. if the cpu detects that the crystal clock is not operating correctly, it c an switch to the slow rc oscillator as a less accurate, but still func- tional, backup solution. table 7-2. start-up times for the calib rated fast rc oscillator sut1:0 start-up time from power-down and power-save additional delay from reset 00 6 ck 14ck 01 6 ck 14ck + 3.9 ms 10 6 ck 14ck + 62.5 ms 11 reserved table 7-3. number of ultra low po wer rc oscillator cycles typ time-out number of cycles 3.9 ms 500 62.5 ms 8000
29 2548f?avr?03/2013 atmega406 7.11 register description 7.11.1 fosccal ? fast rc os cillator calibration register ? bits 7:0 ? fcal7:0: fast rc oscillator calibration value the fast rc oscillator calibration register is used to trim the fast rc os cillator to remove pro- cess variations from the oscillator frequency. the factory-calibrated value is automatically written to this register during chip reset, givi ng an oscillator frequency of 4.0 mhz at 25c. the application software can write th is register to change the oscilla tor frequency. the oscillator can be calibrated to any frequency in the range 3.7 - 4.0 mhz within 1% accuracy. calibration out- side that range is not guaranteed. note that this o scillator is used to time eeprom and flash write accesses , and these write times will be affected accordingly. if the eeprom or flash are writ ten, do not calibrate to more than 4.4 mhz. other wise, the eeprom or flash write may fail. the fcal7 bit determines the range of operation for the oscillator. setting this bit to 0 gives the lowest frequency range, setting this bit to 1 gives the highest frequency range. the two fre- quency ranges are overlapping, in other words a setting of fosccal = 0x7f gives a higher frequency than fosccal = 0x80. the fcal6:0 bits are used to tune the frequency within the selected range. a setting of 0x00 gives the lowest frequency in that range, and a se tting of 0x7f gives the highest frequency in the range. incrementing fcal6:0 by 1 will give a fr equency increment of less than 2% in the fre- quency range 3.7 - 4.0 mhz. 7.11.2 ccsr ? clock control and status register ? bits 7:2 - res: reserved bits these bits are reserved bits in the atmega406 and will always read as zero. ? bit 1 - xoe: 32 khz crystal oscillator enable the xoe bit is used to enable the 32 khz crystal oscillator before it is se lected as clock source. this allows the oscillator clock to stabilize prio r to use. the 32 khz crystal oscillator requires approximately two seconds to stab ilize, this must be timed by th e user software. if the software tries to write a one to acs and a zero to xo e at the same time, both xoe and acs will be cleared by the hardware. thus, while the 32 khz crystal oscillator is disabled it is not possible to select it as a clock source . bit 76543210 (0x66) fcal7 fcal6 fcal5 fcal4 fcal3 fcal2 fcal1 fcal0 fosccal read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value device specific calibration value bit 76543210 (0xc0) ? ? ? ? ? ? xoe acs ccsr read/write r r r r r r r/w r/w initial value00000000
30 2548f?avr?03/2013 atmega406 ? bit 0 - acs: asynchronous clock select the acs bit is used to selected the source of the asynchronous clock for the coulomb counter adc and wake-up timer. the slow rc oscillator is selected when this bit is cleared (zero). the 32 khz crystal oscillator is sele cted when this bit is set (one). the selected clock source and oscillator enable cond itions are illustrated in table 7-4 . recommended algorithm for switchi ng from the rc oscillator to the crystal oscillator as the asynchronous clock for the coulomb counter adc and wake-up timer: 1. enable the crystal oscillator by setting the xoe bit (one). 2. enable the wake-up timer, select a two second timeout, and reset the wake-up timer ( ?wake-up timer? on page 49 for details). 3. wait for the wake-up timer time-out. 4. switch to the crystal oscilla tor by setting the acs bit (one) while keeping the xoe bit set (one). 5. optional: wait for an other wake-up timer time -out, to ensure the crystal oscillator is operating correctly. this can be done by enab ling another timer interr upt with significantly longer time-out, and checking that the wake-up timer time-out occurs first. recommended algorithm for switching from the crys tal oscillator to the rc oscillator as the asynchronous clock for the coulomb counter adc and wake-up timer: 1. switch to the rc oscillator by clearing the acs bit (zero) while ke eping the xoe bit set (one). 2. disable the crystal oscillator by clearing t he xoe bit (zero) while keeping the acs bit cleared (zero). table 7-4. asynchronous clock source and oscillator enable conditions sleep mode 32 khz crystal oscillator enable slow rc oscillator enable power-off or power-down 0 0 other sleep modes xoe acs & (caden | wuten) active mode xoe 1
31 2548f?avr?03/2013 atmega406 8. power management and sleep modes sleep modes enable the application to shut down unused modules in the mcu, thereby saving power. the avr provides various sleep modes allowing the user to tailor the power consump- tion to the application?s requirements. to enter any of the five slee p modes, the se bit in smcr mu st be written to logic one and a sleep instruction must be executed. the sm2:0 bits in the smcr register select which sleep mode (idle, adc noise reduction, power-down, po wer-save, or power-off) will be activated by the sleep instruction. see table 8-1 for a summary. if an enabled interrupt occurs while the mcu is in a sleep mode, the mcu wakes up. the mcu is then halted for four cycles in addition to the start-up time, executes the interrupt routine, and resumes execution from the instruction following sleep. the contents of the register fi le and sram are unal tered when the device wakes up from any sleep mode except power-off. if a reset occurs during sleep mode, the mcu wakes up and executes from the reset vector . the mcu will reset when returning from power- off mode. figure 7-1 on page 25 presents the different clock systems in the atmega406, and their distri- bution. the figure is helpful in selecting an appropriate sleep mode. 8.0.1 smcr ? sleep mode control register the sleep mode control register contai ns control bits for power management. ? bits 7:4 ? res: reserved bits these bits are reserved bits in the atmega406, and will always read as zero. ? bits 3:1 ? sm2:0: sleep mode select bits 2, 1 and 0 these bits select between the five available sleep modes as shown in table 8-1 . note: 1. smcr is auto-cleared after 4 cycles when this value is set and the se bit is written to logic one. to enter this mode, exec ute sleep instruction within 4 cycl es after writing se to logic one. bit 76543210 0x33 (0x53) ? ? ? ? sm2 sm1 sm0 se smcr read/write r r r r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 8-1. sleep mode select sm2 sm1 sm0 sleep mode 000idle 0 0 1 adc noise reduction 010power-down 011power-save 100power-off (1) 101reserved 110reserved 111reserved
32 2548f?avr?03/2013 atmega406 ? bit 0 ? se: sleep enable the se bit must be written to logic one to make the mcu enter the sleep mode when the sleep instruction is executed. to avoid the mcu entering the sleep mode unless it is the programmer?s purpose, it is recommended to wr ite the sleep enable (se) bit to one just before the execution of the sleep instruction and to clear it immediately af ter waking up. 8.1 idle mode when the sm2:0 bits are written to 000, the sleep instruction makes the mcu enter idle mode, stopping the cpu but allowing all peripheral func tions to continue operating. this sleep mode basically halts clk cpu and clk flash , while allowing the other clocks to run. idle mode enables the mcu to wake up from ex ternal triggered interrup ts as well as internal ones like the timer over- flow interrupt. 8.2 adc noise reduction mode when the sm2:0 bits are written to 001, the sleep instruction makes the mcu enter adc noise reduction mode, stopping the cpu but allowing the voltage adc (v-adc), wake-up timer (wut), watchdog timer (wdt), coulomb counter (cc), current battery protection (cbp), voltage battery protection (vbp), wake-up on regular current (wurc), 32 khz crystal oscillator (xosc_32k) or slow rc oscilla tor (rcosc_slow), the ultra low power rc oscillator (rcosc_ulp), and th e fast rc oscillator (rcosc_f ast) to contin ue operating. this sleep mode basically halts clk i/o , clk cpu , and clk flash , while allowing the other clocks to run. this improves the noise environment for th e voltage adc, enabling higher resolution measurements. 8.3 power-save mode when the sm2:0 bits are written to 011, the sleep instruction makes the mcu enter power- save mode. in this mode, the internal fast rc oscillator (rcosc_fast) is stopped, while wake-up timer (wut), watchdog timer (wdt), coulomb counter (cc), current battery pro- tection (cbp), voltage ba ttery protection (vbp), wake-up on regular current (wurc), 32 khz crystal oscillator (xosc _32k) or slow rc oscillator (rco sc_slow) and the ultra low power rc oscillator (rcosc_ulp ) continue operating. this mode will be the default mode when application so ftware does not re quire operation of cpu, flash or any of the periphe ry units running at the fast internal o scillator (rcosc_fast). if the current through the sense resistor is so small that the coulomb counter cannot measure it accurately, regular current detection should be enabled to reduce power consumption. the wut keeps accurately track of the time so th at battery self discharge can be calculated. note that if a level triggered interrupt is us ed for wake-up from power-save mode, the changed level must be held for some time to wake up the mcu. refer to ?external interrupts? on page 56 for details. when waking up from power-save mode, there is a delay from the wake-up condition occurs until the wake-up becomes effectiv e. this allows the clock to restart and become stable after having been stopped. the wake-up period is defined in ?clock sources? on page 26 .
33 2548f?avr?03/2013 atmega406 8.4 power-down mode when the sm2:0 bits are written to 010, the sleep instruction makes the mcu enter power- down mode. in this mode, the fast rc oscill ator (rcosc_fast), 32 khz crystal oscillator (xosc_32k), and slow rc oscillator (rcosc_s low) are stopped, while the the ultra low power rc oscillator (rcosc_ulp), external inte rrupts, the batt ery protection and the watch- dog continue to operate (if enabled). note that if a level triggered interrupt is used for wake-up from power-down mode, the changed level must be held for some time to wake up the mcu. for more details, see ?external interrupts? on page 56 . when waking up from power-down mode, a delay from the wake-up condi tion occurs until the wake-up becomes effective. this allows the clock to restart and become stable after having been stopped. the wake-up period is defined in ?clock sources? on page 26 . 8.5 power-off mode when the sm2:0 bits are writt en to 100, the sleep instructi on makes the cpu ask the voltage regulator to shut off power to the cpu, leaving only the regulator and the charger detect cir- cuitry to be operational. to ensure that the mc u enters power-off mode only when intended, the sleep instruction must be executed within 4 clock cycles afte r the sm2..0 bi ts are written. note that before entering power-off sleep mode, interrupts should be disabled by software. oth- erwise interrupts may pr event the sleep instruction from bei ng executed within the time limit. table 8-2. active modules in different sleep modes module mode active idle adc nrm power- save power- down power- off rcosc_fast x x x rcosc_ulp xxxxx xosc_32k/ rcosc_slow xxxx cpu x flash x 8-bit timer/16-bit timer x x smbus x x x (1) x (1) x (1) v-adc x x x cc-adc x x x x external interrupts x x x x x cbp (2) xxxxx vbp xxxxx wdt xxxxx
34 2548f?avr?03/2013 atmega406 note: 1. address match and bus connect/disconnect wake-up only. 2. when discharge-fet is switched off, short-ci rcuit protection is autom atically disabled to reduce current consumption. the sleep mode state diagram is shown in figure 8-1 . wut x x x x vreg xxxxxx charger_detect x table 8-3. wake-up sources for sleep modes mode wake-up sources wake-up on regular current battery protection interrupts external interrupts smbus address match and bus connect/disconnect wdt wut spm/eeprom ready cc-adc v-adc other i/o charger connect idle xxx x xxxxxx adc nrm xxx x xxxxx power-save xxx x xx x power-down xx x x power-off x table 8-2. active modules in differen t sleep modes (continued) module mode active idle adc nrm power- save power- down power- off
35 2548f?avr?03/2013 atmega406 figure 8-1. sleep mode state diagram reset active power-off regulator-on power-down power-save interrupt sleep interrupt sleep deep under-voltage deep under-voltage reset from all states reset time-out sleep or deep under-voltage charger connected idle interrupt sleep deep under-voltage adc nrm interrupt sleep deep under-voltage
36 2548f?avr?03/2013 atmega406 8.6 power reduction register the power reduction register, prr, provides a me thod to stop the clock to individual peripher- als to reduce power consumption. the current state of the peripheral is frozen and the i/o registers can not be written. resources used by the peripheral when stopping the clock will remain occupied, hence the peripheral should in most cases be disabled before stopping the clock. waking up a module, whic h is done by clearing the bit in prr, puts the module in the same state as before shutdown. module shutdown can be used in idle mode and ac tive mode to significantly reduce the overall power consumption. in all other sleep modes, the clock is already stopped. 8.6.1 prr0 ? power reduction register 0 ? bit 7:4 - res: reserved bits these bits are reserved in atme ga406 and will always read as zero. ? bit 3 - prtwi: power reduction twi writing a logic one to this bit shuts down the twi by stopping the clock to the module. when waking up the twi again, the twi should be re initialized to ensure proper operation. ? bit 2 - prtim1: power reduction timer/counter1 writing a logic one to this bit shuts down the timer/counter1 module. when the timer/counter1 is enabled, operation will cont inue like before the shutdown. ? bit 1 - prtim0: power reduction timer/counter0 writing a logic one to this bit shuts down the timer/counter0 module. when the timer/counter0 is enabled, operation will cont inue like before the shutdown. ? bit 0 - prvadc: power reduction v-adc writing a logic one to this bit shuts down the v-adc. the v-adc must be disabled before shut down. bit 7654 3 2 1 0 (0x64) ????prtwiprtim1prtim0prvadcprr0 read/writerrrrr/wr/wr/wr/w initial value0000 0 0 0 0
37 2548f?avr?03/2013 atmega406 8.7 minimizing power consumption there are several issues to consider when tryi ng to minimize the power consumption in an avr controlled system. in general, sleep modes shoul d be used as much as possible, and the sleep mode should be selected so that as few as possi ble of the device?s func tions are operating. all functions not needed should be disabled. in parti cular, the following modules may need special consideration when trying to achieve th e lowest possible power consumption. 8.7.1 watchdog timer if the watchdog timer is not neede d in the application, the module should be turn ed off. if the watchdog timer is enabled, it will be enabled in all sleep modes except power-off. the watch- dog timer current consumption is significant only in power-down mode. see ?watchdog timer? on page 43 for details on how to configure the watchdog timer. 8.7.2 port pins when entering a sleep mode, all port pins should be configured to use minimum power. the most important is then to ensure that no pins drive resistive loads. in sleep modes where both the i/o clock (clk i/o ) and the adc clock (clk adc ) are stopped, the input buffers of the device will be disabled. this ensures that no power is c onsumed by the input lo gic when not needed. in some cases, the input logic is needed for detec ting wake-up conditions, and it will then be enabled. see ?digital input enable and sleep modes? on page 64 for details on which pins are enabled. if the input buffer is enabled and the input signal is left floating or have an analog signal level close to v reg /2, the input buffer will use excessive power. for analog input pins, the digital input buffer should be disabled at all times. an analog signal level close to v reg /2 on an input pin can cause significant current even in active mode. digital input buffers can be disabled by writing to the digital inpu t disable register. refer to ?didr0 ? digital input disable register 0? on page 120 for details. 8.7.3 on-chip debug system if the on-chip debug system is enabled by ocde n fuse and the chip enters sleep mode, the main clock source is enabled, and hence, alwa ys consumes power. in the deeper sleep modes, this will contribute significantly to the total current consumption. 8.7.4 battery protection if one of the battery protection features is not needed by the application, this feature should be disabled, see ?bpcr ? battery protection control register? on page 128 . when the discharge fet is switched off, the short- circuit circuitry will auto matically be stopped in order to minimize power consumption. the current consumption in the battery protection ci rcuitry is only signifi- cant in power-down mode. 8.7.5 voltage adc if enabled, the v-adc will consume power independent of sleep mode. to sa ve power, the v- adc should be disabled when not used, and bef ore entering power-save or power-down sleep modes. see ?voltage adc ? 10-channel general pur pose 12-bit sigma-delta adc? on page 116 for details on v-adc operation.
38 2548f?avr?03/2013 atmega406 8.7.6 coloumb counter if enabled, the cc-adc will consume power inde pendent of sleep mode. to save power, the cc-adc should be disabled when not used, an d before entering power-down sleep mode. see ?coulomb counter - dedicated fuel gauging sigma-delta adc? on page 106 for details on cc- adc operation.
39 2548f?avr?03/2013 atmega406 9. system control and reset 9.1 resetting the avr during reset, all i/o registers are set to their initial values, and the pr ogram starts execution from the reset vector. the instruction placed at the reset vector must be a jmp ? absolute jump ? instruction to the reset handling routine. if the program never enables an interrupt source, the interrupt vectors are not used, and regular program code can be placed at these locations. this is also the case if the reset vector is in the app lication section while the interrupt vectors are in the boot section or vice versa. the circuit diagram in figure 9-1 shows the reset logic. the i/o ports of the avr are immediately reset to their initial state when a reset source goes active. this does not require any clock source to be running. after all reset sources have gone inactive, a delay counter is invoked, stretching the internal reset. this allows the voltage regulator to reach a stable level before normal operation starts. the time-out period of the delay counter is defi ned by the user through the sut fuses. the dif- ferent selections for the delay period are presented in ?clock sources? on page 26 . 9.2 reset sources the atmega406 has se veral reset sources: ? power-on reset. if the chip is in power-off mode, the charger detect module generates a reset pulse when a charger is connected.see ?power-on reset and charger connect? on page 40 for details. ? external reset. the mcu is re set when a low level is presen t on the reset pin for longer than the minimum pulse length. see ?external reset? on page 41 for details. ? watchdog reset. the mcu is reset when the watchdog timer period expires and the watchdog is enabled. see ?watchdog reset? on page 42 for details. ? brown-out reset. the mcu is reset when vr eg is below the brown-out reset threshold, v bot . see ?brown-out detection? on page 42 for details. ? jtag avr reset. the mcu is reset as long as th ere is a logic one in the reset register, one of the scan chains of the jtag system. see ?jtag interface and on-chip debug system? on page 171 for details.
40 2548f?avr?03/2013 atmega406 figure 9-1. reset logic 9.2.1 power-on reset and charger connect to be able to start from power-off, a charger must be detected. in order to detect a charger, the voltage at the batt pin must rise above the charger-on threshold voltage level,v cot . this will issue a power- on reset (por), and the chip enters reset mode. wh en the delay counter times out, the chip will enter active mode. table 30-3 on page 230 shows the power-on reset characteristics. mcu status register (mcusr) reset circuit delay counters ck timeout wdrf extrf porf data b u s clock generator spike filter pull-up resistor jtrf bodrf jtag reset register ultra low power rc oscillator sut[1:0] power-on reset circuit/ charger detect watchdog timer reset batt por v reg counter reset brown-out detection v reg
41 2548f?avr?03/2013 atmega406 figure 9-2. power-on reset in operation. 9.2.2 external reset an external reset is generated by a low level on the reset pin. reset pulses longer than the minimum pulse width (see table 30-3 on page 230 ) will generate a reset, even if the clock is not running. shorter pulses are not guaranteed to generate a reset. when the applied signal reaches the reset threshold voltage ? v rst ? on its positive edge, the delay counter starts the mcu after the time-out period ? t tout ? has expired. figure 9-3. external reset during operation v batt v cot sleep_mode por internal_reset power-off reset active timeout t tout fet
42 2548f?avr?03/2013 atmega406 9.2.3 watchdog reset when the watchdog times out, it will generate a short reset pulse of one ck cycle duration. on the falling edge of this pulse, the delay ti mer starts counting the time-out period t tout . refer to page 43 for details on operation of the watchdog timer. figure 9-4. watchdog reset du ring operation 9.2.4 brown-out detection atmega406 has an on-chip brown-out detection (bod) circuit for monitoring the vreg level during operation by comparing it to a fixed trigger level v bot = 2.7v. the trigger level has a hys- teresis to ensure spike free brown-out detection. the hysteresis on th e detection level should be interpreted as v bot+ = v bot + v hyst /2 and v bot- = v bot - v hyst /2. the bod is automatically enab led in all modes of operation, except in power-off mode. when the bod is enabled, and vreg decreases to a value below the trigger level (v bot- in fig- ure 9-5 ), the brown-out reset is immediately activated. when v cc increases above the trigger level (v bot+ in figure 9-5 ), the delay counter starts the mcu after the time-out period t tout has expired. figure 9-5. brown-out reset during operation ck fet vreg reset time-out internal reset v bot- v bot+ t tout
43 2548f?avr?03/2013 atmega406 9.3 watchdog timer atmega406 has an enhanced watchdog timer (wdt). the main features are: ? clocked from separat e on-chip oscillator ? 3 operating modes ?interrupt ? system reset ? interrupt and system reset ? selectable time-out period from 16ms to 8s ? possible hardware fuse watchdog always on (wdton) for fail-safe mode figure 9-6. watchdog timer the watchdog timer (wdt) is a timer counting c ycles of the ultra low power rc oscillator that runs at 128 khz. the wdt gives an interrupt or a system reset when the counter reaches a given time-out value. in normal operation mode, it is required that the system uses the wdr - watchdog timer reset - instruction to restart the counter before the time-out value is reached. if the system doesn't restart th e counter, an inte rrupt or system reset will be issued. in interrupt mode, the wdt gives an interrupt when the timer expires. this interrupt can be used to wake the device from sleep-modes, and also as a general system timer. one example is to limit the maximum time allowed for certain opera tions, giving an interrupt when the operation has run longer than expected. in system reset mode, the wdt gives a reset when the timer expires. this is typically used to prevent sys tem hang-up in case of runaway code. the third mode, interrupt and system reset mode, combines the other two modes by first giving an inter- rupt and then switch to system reset mode. th is mode will for instance allow a safe shutdown by saving critical parameters before a system reset. the watchdog always on (wdton ) fuse, if programmed, will forc e the watchdog timer to sys- tem reset mode. with the fuse programmed the system reset mode bit (wde) and interrupt mode bit (wdie) are locked to 1 and 0 respectively. to further ensure program security, altera- tions to the watchdog set-up must follow timed sequences. th e sequence for clearing wde and changing time-out configuration is as follows: ultra low power rc oscillator 16ms 32ms 64ms 125ms 250ms 0.5s 1.0s 2.0s 4.0s 8.0s wdp0 wdp1 wdp2 wdp3 watchdog reset wde wdif wdie mcu reset interrupt
44 2548f?avr?03/2013 atmega406 1. in the same operation, write a logic one to the watchdog change enable bit (wdce) and wde. a logic one must be written to wde regardless of the previous value of the wde bit. 2. within the next four clock cycles, write th e wde and watchdog prescaler bits (wdp) as desired, but with the wdce bit cleared. this must be done in one operation. the following code example shows one assembly and one c function for turning off the watch- dog timer. the example assumes that interrupts are controlled (e.g. by disabling interrupts globally) so that no interrupts will occur during th e execution of these functions. note: 1. see ?about code examples? on page 7 . assembly code example (1) wdt_off: ; turn off global interrupt cli ; reset watchdog timer wdr ; clear wdrf in mcusr in r16, mcusr andi r16, (0xff & (0< 45 2548f?avr?03/2013 atmega406 note: if the watchdog is accident ally enabled, for example by a runaway pointer or brown-out condition, the device will be reset and the watchdog timer will stay enabled. if the code is not set up to handle the watchdog, this might lead to an eternal loop of time-out resets. to avoid this situation, the application software should a lways clear the watchdog system reset flag (wdrf) and the wde control bit in the initialisatio n routine, even if the watchdog is not in use. the following code example shows one assembly and one c function for changing the time-out value of the watchdog timer. note: 1. ?about code examples? on page 7 . note: the watchdog timer should be reset befo re any change of the wdp bits, since a change in the wdp bits can result in a time-out when switching to a shorter time-out period. assembly code example (1) wdt_prescaler_change: ; turn off global interrupt cli ; reset watchdog timer wdr ; start timed sequence in r16, wdtcsr ori r16, (1< 46 2548f?avr?03/2013 atmega406 9.4 register description 9.4.1 mcusr ? mcu status register the mcu status register provides information on which reset source caused an mcu reset. ? bits 7:5 ? res: reserved bits these bits are reserved bits in the atmega406, and will always read as zero. ? bit 4 ? jtrf: jtag reset flag this bit is set if a reset is being caused by a logic one in the jtag reset register selected by the jtag instruction avr_reset. this bit is rese t by a power-on reset, or by writing a logic zero to the flag. ? bit 3 ? wdrf: watchdog reset flag this bit is set if a watchdog re set occurs. the bit is reset by a power-on reset, or by writing a logic zero to the flag. ? bit 2 ? bodrf: brown-out reset flag this bit is set if a brown-out reset occurs. the bi t is reset by a power-on reset, or by writing a logic zero to the flag. ? bit 1 ? extrf: external reset flag this bit is set if an external reset occurs. the bit is reset by a power-on reset, or by writing a logic zero to the flag. ? bit 0 ? porf: power-on reset flag this bit is set if a power-on reset occurs. the bit is reset only by writing a logic zero to the flag. to make use of the reset flags to identify a rese t condition, the user should read and then reset the mcusr as early as possible in the program. if the register is cleared before another reset occurs, the source of the reset can be found by examining the reset flags. bit 76543210 0x34 (0x54) ? ? ? jtrf wdrf bodrf extrf porf mcusr read/write r r r r/w r/w r/w r/w r/w initial value 0 0 0 see bit description
47 2548f?avr?03/2013 atmega406 9.4.2 wdtcsr ? watchdog timer control register ? bit 7 - wdif: watchdog interrupt flag this bit is set when a time-out occurs in the watchdog timer and the watchdog timer is config- ured for interrupt. wdif is cleared by hardw are when executing the corresponding interrupt handling vector. alternatively, wdif is cleared by writing a logic one to the flag. when the i-bit in sreg and wdie are set, the watchdog time-out interrupt is executed. ? bit 6 - wdie: watchdog interrupt enable when this bit is written to one and the i-bit in t he status register is set, the watchdog interrupt is enabled. if wde is cleared in combination with this setting, the watchdog timer is in interrupt mode, and the corresponding interrupt is execut ed if time-out in the watchdog timer occurs. if wde is set, the watchdog timer is in interrupt and system reset mode. the first time-out in the watchdog timer will set wdif. executing t he corresponding interrup t vector will clear wdie and wdif automatically by hardw are (the watchdog goes to system reset mode). this is use- ful for keeping the watchdog timer security while using the interrupt. to stay in interrupt and system reset mode, wdie must be set after each interrupt. this should however not be done within the interrupt service routine itself, as th is might compromise the safety-function of the watchdog system reset mode. if the interrupt is not executed before the next time-out, a sys- tem reset will be applied. ? bit 5, 2:0 - wdp3:0 : watchdog timer prescaler 3, 2, 1 and 0 the wdp3:0 bits determine the watchdog ti mer prescaling when the watchdog timer is enabled. the different prescaling values and th eir corresponding timeout periods are shown in table 9-2 . ? bit 4 - wdce: watchdog change enable this bit is used in timed sequences for changi ng wde and prescaler bits. to clear the wde bit, and/or change the prescaler bits, wdce must be set. once written to one, ha rdware will clear wdce after four clock cycles. bit 76543210 (0x60) wdif wdie wdp3 wdce wde wdp2 wdp1 wdp0 wdtcsr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 x 0 0 0 table 9-1. watchdog timer configuration wdton wde wdie mode ac tion on time-out 0 0 0 stopped none 0 0 1 interrupt mode interrupt 0 1 0 system reset mode reset 011 interrupt and system reset mode interrupt, then go to system reset mode 1 x x system reset mode reset
48 2548f?avr?03/2013 atmega406 ? bit 3 - wde: watchdog system reset enable wde is overridden by wdrf in mcusr. this m eans that wde is always set when wdrf is set. to clear wde, wdrf must be cleared first. this feature ensures multiple resets during con- ditions causing failure, and a safe start-up after the failure. ? bits 5, 2:0 ? wdp3:0: watchdog timer prescaler 3, 2, 1, and 0 the wdp3:0 bits determine the watchdog ti mer prescaling when the watchdog timer is enabled. the different prescaling values and th eir corresponding timeout periods are shown in table 9-2 .. table 9-2. watchdog timer prescale select wdp3 wdp2 wdp1 wdp0 number of wdt oscillator cycles typical time-out at v cc = 3.3v 0 0 0 0 2k cycles 16 ms 0 0 0 1 4k cycles 32 ms 0 0 1 0 8k cycles 64 ms 0 0 1 1 16k cycles 0.125 s 0 1 0 0 32k cycles 0.25 s 0 1 0 1 64k cycles 0.5 s 0 1 1 0 128k cycles 1.0 s 0 1 1 1 256k cycles 2.0 s 1 0 0 0 512k cycles 4.0 s 1 0 0 1 1024k cycles 8.0 s 1010 reserved 1011 1100 1101 1110 1111
49 2548f?avr?03/2013 atmega406 10. wake-up timer the following section describes the wake-up timer in the atmega406. ? one wake-up timer interrupt ? 8 selectable time-out periods ? separate wake-up timer calibration flag ? separate clock source 10.1 overview the wake-up timer is clocked eit her from the slow rc oscillator or from the external 32 khz crystal oscillator. see ?run-time clock source select? on page 28 for details. by controlling the wake-up timer prescaler, the wake-up interval can be adjusted from 31.25 ms to 4 s. eight dif- ferent clock cycle periods can be selected to determine the time-out period. figure 10-1. wake-up timer 10.2 register description 10.2.1 wutcsr ? wake-up timer control and status register ? bit 7 ? wutif: wake-up timer interrupt flag the wutif bit is set (one) when an overflow o ccurs in the wake-up timer. wutif is cleared by hardware when executing the corr esponding interrupt handling vect or. alternatively, wutif is cleared by writing a logic one to the flag. when the sreg i-bit, wutie (wake-up timer interrupt enable), and wutif are set (one), the wake-up timer interrupt is executed. slow rc oscillator clk wut /1k clk wut /2k clk wut /4k clk wut /8k clk wut /16k clk wut /32k clk wut /64k clk wut /128k clk wut /64 wake-up wutr wutp0 wutp1 wutp2 wute wutif wutcf 32 khz oscillator 1/4 prescaler clk wut bit 765 4 3210 (0x62) wutif wutie wutcf wutr wute wutp2 wutp1 wutp0 wutcsr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
50 2548f?avr?03/2013 atmega406 ? bit 6 ? wutie: wake-up timer interrupt enable when the wutie bit and the i-bit in the status register are set (one), the wake-up timer inter- rupt is enabled. the corresponding interrupt is executed if a wake-up timer overflow occurs, i.e., when the wutif bit is set. ? bit 5 ? wutcf: wake-up timer calibration flag the wutcf bit is set every 1.95 ms (256 slow rc oscillator clocks or 64 32 khz crystal oscil- lator clocks). wutcf is cleared by writing a logic one to the flag. wutcf can be used to calibrate the fast rc oscilla tor to the 32 khz oscillator or the slow rc oscillator. ? bit 4 ? wutr: wake-up timer reset when wutr bit is written to one , the wake-up timer is reset, and starts counting from zero. the wutr bit is always read as zero. ? bit 3 ? wute: wake-up timer enable when the wute bit is set (one) the wake- up timer is enabled, and if the wute is cleared (zero) the wake-up timer functi on is disabled. it is recommended to reset the wake-up timer when enabling it, by simultaneously setting the wutr and wute bits. ? bits 2:0 ? wutp2, wutp1, wutp0: w ake-up timer prescaler 2, 1, and 0 the wutp2, wutp1 and wutp0 bits determine the wake-up timer prescaling when the wake-up timer is enabled. the different prescaling values and their corresponding time-out periods are shown in table 10-1 . the wake-up timer should always be reset when changing these bits. table 10-1. wake-up timer pr escale select wutp2 wutp1 wutp0 number of slow rc oscillator cycles number of 32khz crystal oscillator cycles typical time-out 0 0 0 4k(4096) 1k(1024) 31.25 ms 0 0 1 8k(8192) 2k(2048) 62.5 ms 0 1 0 16k(16384) 4k(4096) 125 ms 0 1 1 32k(32768) 8k(8192) 250 ms 1 0 0 64k(65536) 16k(16384) 0.5 s 1 0 1 128k(131072) 32k(32768) 1 s 1 1 0 256k(262144) 64k(65536) 2 s 1 1 1 512k(524288) 128k(131072) 4 s
51 2548f?avr?03/2013 atmega406 11. interrupts this section describes the specifics of the inte rrupt handling as performed in atmega406. for a general explanation of the avr in terrupt handling, refer to ?reset and interrupt handling? on page 14 . 11.1 interrupt vectors in atmega406 notes: 1. when the bootrst fuse is programmed, the device will jump to the boot loader address at reset, see ?boot loader support ? read-while-write self-programming? on page 178 . 2. when the ivsel bit in mcucr is set, interrupt vectors will be mo ved to the start of the boot flash section. the address of each interrupt vector will then be the address in this table added to the start address of the boot flash section. table 11-2 shows reset and interrupt vectors plac ement for the various combinations of bootrst and ivsel settings. if the program never enables an in terrupt source, the interrupt table 11-1. reset and interrupt vectors vector no. program address (2) source interrup t definition 1 0x0000 (1) reset external pin, power-on reset, brown-out reset, watchdog reset, and jtag avr reset 2 0x0002 bpint battery protection interrupt 3 0x0004 int0 external interrupt request 0 4 0x0006 int1 external interrupt request 1 5 0x0008 int2 external interrupt request 2 6 0x000a int3 external interrupt request 3 7 0x000c pcint0 pin change interrupt 0 8 0x000e pcint1 pin change interrupt 1 9 0x0010 wdt watchdog time-out interrupt 10 0x0012 wake_up wake-up timer overflow 11 0x0014 timer1 comp timer 1 compare match 12 0x0016 timer1 ovf timer 1 overflow 13 0x0018 timer0 compa timer 0 compare match a 14 0x001a timer0 compb timer 0 compare match b 15 0x001c timer0 ovf timer 0 overflow 16 0x001e twi bus c/d two-wire bus connect/disconnect 17 0x0020 twi two-wire serial interface 18 0x0022 vadc voltage adc conversion complete 19 0x0024 ccadc conv cc-adc instantaneous current conversion complete 20 0x0026 ccadc reg cur cc-adc regular current 21 0x0028 ccadc acc cc-adc accumulate current conversion complete 22 0x002a ee ready eeprom ready 23 0x002c spm ready store program memory ready
52 2548f?avr?03/2013 atmega406 vectors are not used, and regular program code can be placed at these locations. this is also the case if the reset vector is in the applicat ion section while the interrupt vectors are in the boot section or vice versa. note: 1. the boot reset address is shown in table 27-7 on page 193 . for the bootrst fuse ?1? means unprogrammed while ?0? means programmed. the most typical and general program setup fo r the reset and interrupt vector addresses in atmega406 is: table 11-2. reset and interrupt vectors placement (1) bootrst ivsel reset address inte rrupt vectors start address 1 0 0x0000 0x0002 1 1 0x0000 boot reset address + 0x0002 0 0 boot reset address 0x0002 0 1 boot reset address boot reset address + 0x0002 address labels code comments 0x0000 jmp reset ; reset handler 0x0002 jmp bpint ; battery protection interrupt handler 0x0004 jmp ext_int0 ; external interrupt request 0 handler 0x0006 jmp ext_int1 ; external interrupt request 1 handler 0x0008 jmp ext_int2 ; external interrupt request 2 handler 0x000a jmp ext_int3 ; external interrupt request 3 handler 0x000c jmp pcint0 ; pin change interrupt 0 handler 0x000e jmp pcint1 ; pin change interrupt 1 handler 0x0010 jmp wdt ; watchdog time-out interrupt 0x0012 jmp wake_up ; wake-up timer overflow 0x0014 jmp tim1_comp ; timer1 compare handler 0x0016 jmp tim1_ovf ; timer1 overflow handler 0x0018 jmp tim0_compa ; timer0 comparea handler 0x001a jmp tim0_compb ; timer0 compareb handler 0x001c jmp tim0_ovf ; timer0 overflow handler 0x001e jmp twi_bus_cd ; two-wire bus connect/disconnect handler 0x0020 jmp twi ; two-wire serial interface handler 0x0022 jmp vadc ; voltage adc conversion complete handler 0x0024 jmp ccadc_conv ; cc-adc instantaneous current conversion complete handler 0x0026 jmp ccadc_rec_cur ; cc-adc regular current handler 0x0028 jmp ccadc_acc ; cc-adc accumulate current conversion complete handler 0x002a jmp ee_rdy ; eeprom ready handler 0x002c jmp spm_rdy ; store program memory ready handler ; 0x002e reset: ldi r16, high(ramend) ; main program start 0x002f out sph,r16 ; set stack pointer to top of ram 0x0030 ldi r16, low(ramend) 0x0031 out spl,r16 0x0032 sei ; enable interrupts 0x0033 xxx 0x0034 ... ... ... ;
53 2548f?avr?03/2013 atmega406 when the bootrst fuse is u nprogrammed, the bo ot section size set to 2k bytes and the ivsel bit in the mcucr reg- ister is set before any interrupts are enabled, the most typical and general program setup for the reset and interrupt vector addresses is: address labels code comments 0x0000 reset: ldi r16,high(ramend); main program start 0x0001 out sph,r16 ; set stack pointer to top of ram 0x0002 ldi r16,low(ramend) 0x0003 out spl,r16 0x0004 sei ; enable interrupts 0x0005 xxx ; .org 0x4c02 0x4c02 jmp bpint ; battery protection interrupt handler 0x4c04 jmp ext_int0 ; external interrupt request 0 handler ... ... ... ; 0x4c2c jmp spm_rdy ; store program memory ready handler when the bootrst fuse is programmed and the boot section si ze set to 2k bytes, the most typical and general program setup for the reset and inte rrupt vector addresses is: address labels code comments .org 0x0002 0x0002 jmp bpint ; battery protection interrupt handler 0x0004 jmp ext_int0 ; external interrupt request 0 handler ... ... ... ; 0x002c jmp spm_rdy ; store program memory ready handler ; .org 0x4c00 0x4c00 reset: ldi r16,high(ramend); main program start 0x4c01 out sph,r16 ; set stack pointer to top of ram 0x4c02 ldi r16,low(ramend) 0x4c03 out spl,r16 0x4c04 sei ; enable interrupts 0x4c05 xxx when the bootrst fuse is programmed, the boot section size set to 2k bytes and the ivsel bit in the mcucr register is set before any interrupts are enabled, the most typical and general program setup for the reset and interrupt vector addresses is: address labels code comments ; .org 0x4c00 0x4c00 jmp reset ; reset handler 0x4c02 jmp bpint ; battery protection interrupt handler 0x4c04 jmp ext_int0 ; external interrupt request 0 handler ... ... ... ; 0x4c2c jmp spm_rdy ; store program memory ready handler ; 0x4c2e reset: ldi r16,high(ramend); main program start
54 2548f?avr?03/2013 atmega406 0x4c2f out sph,r16 ; set stack pointer to top of ram 0x4c30 ldi r16,low(ramend) 0x4c31 out spl,r16 0x4c32 sei ; enable interrupts 0x4c33 xxx 11.2 moving interrupts between application and boot space the general interrupt control register controls the placement of the interrupt vector table. assembly code example move_interrupts: ; enable change of interrupt vectors ldi r16, (1< 55 2548f?avr?03/2013 atmega406 11.3 register description 11.3.1 mcucr ? mcu control register ? bit 1 ? ivsel: interrupt vector select when the ivsel bit is cleared (z ero), the interrupt vectors are pl aced at the star t of the flash memory. when this bit is set (one), the interrupt vectors are moved to the beginning of the boot loader section of the flash. the actual address of the start of the boot flash section is deter- mined by the bootsz fuses. refer to the section ?boot loader support ? read-while-write self-programming? on page 178 for details. to avoid unintentional changes of interrupt vector tables, a special write procedure must be followed to change the ivsel bit: a. write the interrupt vector change enable (ivce) bit to one. b. within four cycles, write the desired valu e to ivsel while writ ing a zero to ivce. interrupts will automatically be di sabled while this sequence is executed. interrupts are disabled in the cycle ivce is set, and they remain disabl ed until after the instru ction following the write to ivsel. if ivsel is not written, interrupts remain disabled for four cycles. the i-bit in the status register is unaffected by the automatic disabling. note: if interrupt vectors are placed in the boot loader section and boot lock bit blb02 is pro- grammed, interrupts are disabled while executing fr om the application section. if interrupt vectors are placed in the application section and boot lo ck bit blb12 is programed, interrupts are dis- abled while executing from the boot loader section. refer to the section ?boot loader support ? read-while-write self-programming? on page 178 for details on boot lock bits. ? bit 0 ? ivce: interrupt vector change enable the ivce bit must be wr itten to logic one to ena ble change of the ivsel bit. ivce is cleared by hardware four cyc les after it is written or when ivsel is written. sett ing the ivce bit will disable interrupts, as explained in the ivsel description above. see code example below. bit 76543210 0x35 (0x55) jtd ? ? pud ? ? ivsel ivce mcucr read/write r/w r r r/w r r r/w r/w initial value 0 0 0 0 0 0 0 0
56 2548f?avr?03/2013 atmega406 12. external interrupts 12.1 overview the external interrupts are triggered by the int3:0 pins. observe that, if enabled, the interrupts will trigger even if th e int3:0 pins are configur ed as outputs. this feat ure provides a way of gen- erating a software interrupt. the ex ternal interrupts can be triggered by a falling or rising edge or a low level. this is set up as indicated in the specification for the exter nal interrupt control reg- ister ? eicra. when the external interrupt is en abled and is configured as level triggered, the interrupt will trigger as long as the pin is held low. interrupts are detected asynchronously. this implies that these interrupts can be used for waking the part also from sleep modes other than idle mode. the i/o clock is halted in all sleep modes except idle mode. note that if a level triggered interrupt is used for wake-up from power-down mode, the changed level must be held for some ti me to wake up the mcu. this makes the mcu less sensitive to noise. the changed level is sampled twice by the slow rc oscillator clock. the period of the slow rc oscillator is 7.8 s (nominal) at 25 ? c. the mcu will wake up if the input has the required level during this sampling or if it is held until the end of the start-up time. the start-up time is defined by the sut fuses as described in ?system clock and clock options? on page 25 . if the level is sampled twice by the slow rc oscillator clo ck but disappears befor e the end of the start-up time, the mcu will still wake up, but no interrupt will be generated. the required level must be held long enough for the mcu to complete the wake up to trig ger the level interrupt. 12.2 register description 12.2.1 eicra ? external inte rrupt control register a ? bits 7:0 ? isc31, isc30 - isc01, isc00: external interrupt 3 - 0 sense control bits the external interrupts 3 - 0 are activated by the external pins int3:0 if the sreg i-flag and the corresponding interrupt mask in the eimsk is set. the level and edges on the external pins that activate the interrupts are defined in table 12-1 on page 57 . edges on int3:int0 are registered asynchronously. pulses on int3:0 pins wider than the minimum pulse width given in table 12-2 on page 57 will generate an interrupt. shorter pulses are not guaranteed to generate an inter- rupt. if low level interrupt is se lected, the low level must be held until the completion of the currently executing instru ction to generate an interrupt. if e nabled, a level trig gered inte rrupt will generate an interrupt request as long as the pi n is held low. when c hanging the iscn bit, an interrupt can occur. therefore, it is recommende d to first disable intn by clearing its interrupt enable bit in the eimsk register . then, the iscn bit can be cha nged. finally, the intn interrupt flag should be cleared by writing a logical one to its interrupt flag bit (intfn) in the eifr regis- ter before the interr upt is re-enabled. bit 76543210 (0x69) isc31 isc30 isc21 isc20 isc11 isc10 isc01 isc00 eicra read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
57 2548f?avr?03/2013 atmega406 note: 1. n = 3, 2, 1, or 0. when changing the iscn1/iscn0 bits, the interrupt must be disabled by clearing its interrupt enable bit in the eimsk register. otherwise an interrupt can occur when the bits are changed. 12.2.2 eimsk ? external interrupt mask register ? bits 7:4 ? res: reserved bits these bits are reserved bits ins the atmega406, and will always read as zero. ? bits 3:0 ? int3 - int0: external interrupt request 3 - 0 enable when an int3 ? int0 bit is written to one and t he i-bit in the status register (sreg) is set (one), the corresponding external pin interrupt is enabled. the interrupt sense control bits in the external interrupt control regist er ? eicra ? defines whether the external interrupt is activated on rising or falling edge or level sensed. activi ty on any of these pins will trigger an interrupt request even if the pin is enabled as an output. this provides a way of generating a software interrupt. 12.2.3 eifr ? external interrupt flag register ? bits 7:4 ? res: reserved bits these bits are reserved bits ins the atmega406, and will always read as zero. ? bits 3:0 ? intf3 - intf0: external interrupt flags 3 - 0 when an edge or logic change on the int3:0 pin triggers an interrupt request, intf3:0 becomes set (one). if the i-bit in sreg and the corresp onding interrupt enable bit, int3:0 in eimsk, are table 12-1. interrupt sense control iscn1 iscn0 description (1) 0 0 the low level of intn generates an interrupt request. 0 1 any logical change on intn generates an interrupt request. 1 0 the falling edge of intn generates an interrupt request. 1 1 the rising edge of intn generates an interrupt request. table 12-2. asynchronous external interrupt characteristics symbol parameter condition min typ max units t int minimum pulse width for asynchronous external interrupt 50 ns bit 76543210 0x1d (0x3d) ? ? ? ? int3 int2 int1 int0 eimsk read/write r r r r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x1c (0x3c) ? ? ? ? intf3 intf2 intf1 intf0 eifr read/write r r r r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
58 2548f?avr?03/2013 atmega406 set (one), the mcu will jump to the interrupt vector . the flag is cleared wh en the interr upt routine is executed. alternatively, the flag can be cleared by writing a logical one to it. these flags are always cleared when int3:0 are configured as level interrupt. note that when entering sleep mode with the int3:0 interrupts disabled, the input buffers on these pins will be disabled. this may cause a logic change in internal si gnals which will set the intf3:0 flags. see ?digital input enable and sleep modes? on page 64 for more information. 12.2.4 pcicr? pin change interrupt control register ? bit 7:2 - res: reserved bits these bits are reserved bits in the atmega406, and will always read as zero. ? bit 1 - pcie1: pin change interrupt enable 1 when the pcie1 bit is set (one) and the i-bit in the status register (sreg) is set (one), pin change interrupt 1 is enabled. any change on any enabled pcint15:8 pin will cause an inter- rupt. the corresponding interrupt of pin change interrupt request is executed from the pci1 interrupt vector. pcint15:8 pins are enable d individually by the pcmsk1 register. ? bit 0 - pcie0: pin change interrupt enable 0 when the pcie0 bit is set (one) and the i-bit in the status register (sreg) is set (one), pin change interrupt 0 is enabled. any change on any enabled pcint7 :0 pin will cause an interrupt. the corresponding interrupt of pin change interrupt request is executed from the pci0 inter- rupt vector. pcint7:0 pins are enabled individually by the pcmsk0 register. 12.2.5 pcifr ? pin change interrupt flag register ? bit 7:2 - res: reserved bits these bits are reserved bits in the atmega406, and will always read as zero. ? bit 1 - pcif1: pin change interrupt flag 1 when a logic change on any pcint15:8 pin trigge rs an interrupt request, pcif1 becomes set (one). if the i-bit in sreg and the pcie1 bit in pcicr are set (one), the mcu will jump to the corresponding interrupt vector. the flag is cleared when the interrupt rout ine is executed. alter- natively, the flag can be cleared by writing a logical one to it. ? bit 0 - pcif0: pin change interrupt flag 0 when a logic change on any pcint7:0 pin trigge rs an interrupt request, pcif0 becomes set (one). if the i-bit in sreg and the pcie0 bit in pcicr are set (one), the mcu will jump to the bit 76543210 (0x68) ? ? ? ? ? ? pcie1 pcie0 pcicr read/write rrrrrrr/wr/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x1b (0x3b) ??????pcif1pcif0pcifr read/write rrrrrrr/wr/w initial value 0 0 0 0 0 0 0 0
59 2548f?avr?03/2013 atmega406 corresponding interrupt vector. the flag is cleared when the interrupt rout ine is executed. alter- natively, the flag can be cleared by writing a logical one to it. 12.2.6 pcmsk1 ? pin change mask register 1 ? bit 7:0 ? pcint15:8: pin change enable mask 15:8 each pcint15:8-bit selects w hether pin change interrupt is enabled on the corresponding i/o pin. if pcint15:8 is set and the pcie1 bit in pci cr is set, pin change inte rrupt is enabled on the corresponding i/o pin. if pcint15:8 is cleared, pin change interrupt on the corresponding i/o pin is disabled. 12.2.7 pcmsk0 ? pin change mask register 0 ? bit 7:0 ? pcint7:0: pin change enable mask 7:0 each pcint7:0 bit selects whether pin change interrupt is enabled on the corresponding i/o pin. if pcint7:0 is set and the pcie0 bit in pcicr is set, pin change interrupt is enabled on the cor- responding i/o pin. if pcint7:0 is cleared, pin change inte rrupt on the corresponding i/o pin is disabled. bit 76543210 (0x6c) pcint15 pcint14 pcint13 pcint12 pcint11 pcint10 pcint9 pcint8 pcmsk1 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x6b) pcint7 pcint6 pcint5 pcint4 pcint3 pcint2 pcint1 pcint0 pcmsk0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
60 2548f?avr?03/2013 atmega406 13. low voltage i/o-ports 13.1 introduction all low voltage avr ports have tr ue read-modify-write functionality when used as general digi- tal i/o ports. this means that the direction of one port pin can be changed without unintentionally changing the direction of any other pin with th e sbi and cbi instructio ns. the same applies when changing drive value (if configured as output) or enabling/disabling of pull-up resistors (if configured as input). all low voltage port pins hav e individually selectable pull-up resistors with a supply-voltage invariant resistance. all i/o pins have protection diodes to both v reg and ground as indicated in figure 13-1 on page 60 . refer to ?electrical characteristics? on page 225 for a complete list of parameters. figure 13-1. low voltage i/o pin equivalent schematic all registers and bit references in this section are written in general form. a lower case ?x? repre- sents the numbering letter for the port, and a lower case ?n? represents the bit number. however, when using the register or bit defines in a progr am, the precise form must be used. for example, portb3 for bit no. 3 in port b, here document ed generally as portxn. the physical i/o regis- ters and bit locations are listed in ?register description? on page 73 . three i/o memory address locations are allocated for each low voltage port, one each for the data register ? portx, data direction regist er ? ddrx, and the port input pins ? pinx. the port input pins i/o location is read only, while the data register and the data direction register are read/write. however, writing a logic one to a bi t in the pinx register, will result in a toggle in the corresponding bit in the data register. in addition, the pull-up disable ? pud bit in mcucr disables the pull-up function for all low voltage pins in all ports when set. using the i/o port as general digital i/o is described in ?low voltage ports as general digital i/o? on page 61 . many low voltage port pins are multip lexed with alternate functions for the peripheral features on the device. how each alte rnate function interferes with the port pin is described in ?alternate port functions? on page 66 . refer to the individual module sections for a full description of the alternate functions. note that enabling the alternate function of some of the port pins does not affect the use of the other pins in the port as general digital i/o. c pin logic r pu see figure "general digital i/o" for details pxn
61 2548f?avr?03/2013 atmega406 13.2 low voltage ports as general digital i/o the low voltage ports are bi-directional i/ o ports with optional internal pull-ups. figure 13-2 shows a functional description of one i/o -port pin, here generically called pxn. figure 13-2. general low voltage digital i/o (1) note: 1. wrx, wpx, wdx, rrx, rpx, and rdx are co mmon to all pins within the same port. clk i/o , sleep, and pud are common to all ports. 13.2.1 configuring the pin each port pin consists of three register bits: ddxn, portxn, and pinxn. as shown in ?register description? on page 73 , the ddxn bits are accessed at th e ddrx i/o address, the portxn bits at the portx i/o address, and the pi nxn bits at the pinx i/o address. the ddxn bit in the ddrx register selects the direct ion of this pin. if ddxn is written logic one, pxn is configured as an output pin. if ddxn is written logic ze ro, pxn is configured as an input pin. if portxn is written logic one w hen the pin is configured as an i nput pin, the pull-up resistor is activated. to switch the pull-up re sistor off, portxn has to be wr itten logic zero or the pin has to be configured as an output pin. the port pins are tri-stated when reset condition becomes active, even if no clocks are running. if portxn is written logic one when the pin is configured as an ou tput pin, the port pin is driven high (one). if portxn is writte n logic zero when the pin is config ured as an output pin, the port pin is driven low (zero). clk rpx rrx rdx wdx pud synchronizer wdx: write ddrx wrx: write portx rrx: read portx register rpx: read portx pin pud: pullup disable clk i/o : i/o clock rdx: read ddrx d l q q reset reset q q d q q d clr portxn q q d clr ddxn pinxn data b u s sleep sleep: sleep control pxn i/o wpx 0 1 wrx wpx: write pinx register
62 2548f?avr?03/2013 atmega406 13.2.2 toggling the pin writing a logic one to pinxn toggles the value of portxn, independent on the value of ddrxn. note that the sbi instruction can be us ed to toggle one single bit in a port. 13.2.3 switching between input and output when switching between tri-state ({ddxn, port xn} = 0b00) and output high ({ddxn, portxn} = 0b11), an intermediate state with either pull-up enabled {ddxn, portxn} = 0b01) or output low ({ddxn, portxn} = 0b10) must occur. norma lly, the pull-up enabled state is fully accept- able, as a high-impedant enviro nment will not notice the differenc e between a strong high driver and a pull-up. if this is not the case, the pud bit in the mcucr register can be set to disable all pull-ups in all ports. switching between input with pull-up and output low generates the same problem. the user must use either the tri-state ({ddxn, portxn} = 0b00) or the output high state ({ddxn, portxn} = 0b11) as an intermediate step. table 13-1 summarizes the control signals for the pin value. 13.2.4 reading the pin value independent of the setting of data direction bit ddxn, the port pin can be read through the pinxn register bit. as shown in figure 13-2 , the pinxn register bit and the preceding latch con- stitute a synchronizer. this is needed to avoid metastability if the physical pin changes value near the edge of the internal clock, but it also introduces a delay. figure 13-3 shows a timing dia- gram of the synchronization when reading an externally applied pin value. the maximum and minimum propagation delays are denoted t pd,max and t pd,min respectively. table 13-1. port pin configurations ddxn portxn pud (in mcucr) i/o pull-up comment 0 0 x input no tri-state (hi-z) 0 1 0 input yes pxn will source current if ext. pulled low. 0 1 1 input no tri-state (hi-z) 1 0 x output no output low (sink) 1 1 x output no output high (source)
63 2548f?avr?03/2013 atmega406 figure 13-3. synchronization when reading an externally applied pin value consider the clock period starting shortly after the first falling edge of the system cl ock. the latch is closed when the clock is low, and goes transpa rent when the clock is high, as indicated by the shaded region of the ?sync latch? signal. the signal value is latched when the system clock goes low. it is clocked into the pinxn register at the succeeding positive clock edge. as indi- cated by the two arrows tpd,max and tpd,min, a single signal tr ansition on the pin will be delayed between ? and 1? system clock period depending upon the time of assertion. when reading back a software assigned pin value, a nop instruction must be inserted as indi- cated in figure 13-4 . the out instruction sets the ?sync latch? signal at the positive edge of the clock. in this case, the delay tpd through the synchronizer is 1 system clock period. figure 13-4. synchronization when reading a software assigned pin value the following code example shows how to set port b pins 0 and 1 high, 2 and 3 low, and define the port pins from 4 to 7 as input with pull-ups as signed to port pins 6 and 7. the resulting pin values are read back again, but as previously di scussed, a nop instruction is included to be able to read back the value recently assigned to some of the pins. xxx in r17, pinx 0x00 0xff instructions sync latch pinxn r17 xxx system clk t pd, max t pd, min out portx, r16 nop in r17, pinx 0xff 0x00 0xff system clk r16 instructions sync latch pinxn r17 t pd
64 2548f?avr?03/2013 atmega406 note: 1. for the assembly program, two temporary re gisters are used to minimize the time from pull- ups are set on pins 0, 1, 6, and 7, until the di rection bits are correctly set, defining bit 2 and 3 as low and redefining bits 0 and 1 as strong high drivers. 13.2.5 digital input enable and sleep modes as shown in figure 13-2 , the digital input signal can be clamped to ground at the input of the schmitt-trigger. the signal denot ed sleep in the figure, is set by the mcu sleep controller in power-down mode and power-save mode to avoi d high power consumption if some input sig- nals are left floating, or have an analog signal level close to v reg /2. sleep is overridden for port pins enabled as ex ternal interrupt pins. if the external interrupt request is not e nabled, sleep is active also for these pi ns. sleep is also over ridden by various other alternate functions as described in ?alternate port functions? on page 66 . if a logic high level (?one?) is present on an asyn chronous external interrupt pin configured as ?interrupt on rising edge, falling edge, or any logic change on pin? while the external interrupt is not enabled, the corresponding external interrupt flag will be set when resuming from the above mentioned sleep mode, as the clamping in these sleep mode produces the requested logic change. assembly code example (1) ... ; define pull-ups and set outputs high ; define directions for port pins ldi r16,(1< 65 2548f?avr?03/2013 atmega406 13.2.6 unconnected pins if some pins are unused, it is recommended to ensure that these pins have a defined level. even though most of the digital inputs are disabled in the deep sleep modes as described above, float- ing inputs should be avoided to reduce current consumption in all other modes where the digital inputs are enabled (reset, active mode and idle mode). the simplest method to ensure a defined level of an unused pin, is to enable the internal pull-up. in this case, the pull-up will be disabled during reset. if low po wer consumption during reset is important, it is recommended to use an extern al pull-up or pull-down. connecting unused pins directly to v cc or gnd is not recommended, since this ma y cause excessive curr ents if the pin is accidentally configured as an output.
66 2548f?avr?03/2013 atmega406 13.3 alternate port functions many low voltage port pins have alternate functions in addition to being general digital i/os. fig- ure 13-5 shows how the port pin contro l signals from the simplified figure 13-2 can be overridden by alternate functions. the overriding si gnals may not be present in all port pins, but the figure serves as a generic description applicable to all port pins in the avr microcontroller family. figure 13-5. alternate port functions (1) note: 1. wrx, wpx, wdx, rrx, rpx, and rdx are co mmon to all pins within the same port. clk i/o , sleep, and pud are common to all ports. all other signals are unique for each pin. clk rpx rrx wrx rdx wdx pud synchronizer wdx: write ddrx wrx: write portx rrx: read portx register rpx: read portx pin pud: pullup disable clk i/o : i/o clock rdx: read ddrx d l q q set clr 0 1 0 1 0 1 dixn aioxn dieoexn pvovxn pvoexn ddovxn ddoexn puoexn puovxn puoexn: pxn pull-up override enable puovxn: pxn pull-up override value ddoexn: pxn data direction override enable ddovxn: pxn data direction override value pvoexn: pxn port value override enable pvovxn: pxn port value override value dixn: digital input pin n on portx aioxn: analog input/output pin n on portx reset reset q q d clr q q d clr q q d clr pinxn portxn ddxn data b u s 0 1 dieovxn sleep dieoexn: pxn digital input-enable override enable dieovxn: pxn digital input-enable override value sleep: sleep control pxn i/o 0 1 ptoexn wpx ptoexn: pxn, port toggle override enable wpx: write pinx
67 2548f?avr?03/2013 atmega406 table 13-2 summarizes the function of the overriding signals. the pin and port indexes from fig- ure 13-5 are not shown in the succeeding tables. the overriding signals are generated internally in the modules having the alternate function. the following subsections shortly describe the alte rnate functions for each port, and relate the overriding signals to the alternate function. refer to the alternate function description for further details. table 13-2. generic description of overriding signals for alternate functions signal name full name description puoe pull-up override enable if this signal is set, the pull-up enable is controlled by the puov signal. if this signal is cleared, the pull-up is enabled when {ddxn, portxn, pud} = 0b010. puov pull-up override value if puoe is set, the pull-up is enabled/disabled when puov is set/cleared, regardless of the setting of the ddxn, portxn, and pud register bits. ddoe data direction override enable if this signal is set, the output driver enable is controlled by the ddov signal. if this signal is cleared, the output driver is enabled by the ddxn register bit. ddov data direction override value if ddoe is set, the output driver is enabled/disabled when ddov is set/cleared, regardless of the setting of the ddxn register bit. pvoe port value override enable if this signal is set and the ou tput driver is enabled, the port value is controlled by the pvov signal. if pvoe is cleared, and the output driver is enabled, the port value is controlled by the portxn register bit. pvov port value override value if pvoe is set, the port value is set to pvov, regardless of the setting of the portxn register bit. ptoe port toggle override enable if ptoe is set, the portxn register bit is inverted. dieoe digital input enable override enable if this bit is set, the digital input enable is controlled by the dieov signal. if this signal is cleared, the digital input enable is determined by mcu state (normal mode, sleep mode). dieov digital input enable override value if dieoe is set, the digital input is enabled/disabled when dieov is set/cleared, regardless of the mcu state (normal mode, sleep mode). di digital input this is the digital input to altern ate functions. in the figure, the signal is connected to the output of the schmitt trigger but before the synchronizer. unless the digital input is used as a clock source, the module with the alternate function will use its own synchronizer. aio analog input/output this is the analog input/output to/from alternate functions. the signal is connected directly to the pad, and can be used bi- directionally.
68 2548f?avr?03/2013 atmega406 13.3.1 alternate functions of port a the port a has an alternate function as input pins to the voltage adc. the alternate pin configuration is as follows: ? adc4/int3:0/pcint7:4 ? port a, bit 7:4 analog to digital converter, channel 4. int3 - int0, external interrupt sources 3:0. the pa7:4 pins can serv e as external interrupt sources to the mcu. pcint7 - pcint4, pin change interrupt sources 7:4. the pa7:4 pins can serve as external interrupt sources to the mcu. ? adc3:0/pcint3:0 ? port a, bit 3:0 analog to digital converter, channels 3:0. pcint3 - pcint0, pin change interrupt sources 3:0. the pa3:0 pins can serve as external interrupt sources to the mcu. table 13-3. port a pins alternate functions port pin alternate function pa7 int3 (external interrupt 3) pcint7 (pin change interrupt 7) pa6 int2 (external interrupt 2) pcint6 (pin change interrupt 6) pa5 int1 (external interrupt 1) pcint5 (pin change interrupt 5) pa4 adc4 (adc input channel 4) int0 (external interrupt 0) pcint4 (pin change interrupt 4) pa3 adc3 (adc input channel 3) pcint3 (pin change interrupt 3) pa2 adc2 (adc input channel 2) pcint2 (pin change interrupt 2) pa1 adc1 (adc input channel 1) pcint1 (pin change interrupt 1) pa0 adc0 (adc input channel 0) pcint0 (pin change interrupt 0)
69 2548f?avr?03/2013 atmega406 table 13-4 and table 13-5 relates the alternate functions of port a to the overriding signals shown in figure 13-5 on page 66 . table 13-4. overriding signals for alte rnate functions in pa7:pa4 signal name pa7/int3/ pcint7 pa6/int2/ pcint6 pa5/int1/ pcint5 pa4/adc4 int0/pcint4 puoe0000 puov0000 ddoe 0 0 0 0 ddov 0 0 0 0 pvoe 0 0 0 0 pvov 0 0 0 0 ptoe???? dieoe int3 enable int2 enable int1 enable int0 enable dieov int3 enable int2 enable int1 enable int0 enable di int3 input/ pcint7 input int2 input/ pcint6 input int1 input/ pcint5 input int0 input/ pcint4 input aio ? ? ? adc4 input table 13-5. overriding signals for alte rnate functions in pa3:pa0 signal name pa3/adc3/ pcint3 pa2/adc2/ pcint2 pa1/adc1/ pcint1 pa0/adc0/ pcint0 puoe0000 puov0000 ddoe 0 0 0 0 ddov 0 0 0 0 pvoe 0 0 0 0 pvov 0 0 0 0 ptoe???? dieoe 0 0 0 0 dieov 0 0 0 0 di pcint3 input pcint2 input pcint1 input pcint0 input aio adc3 input adc2 input adc1 input adc0 input
70 2548f?avr?03/2013 atmega406 13.3.2 alternate functions of port b the port b pins with altern ate functions are shown in table 13-6 . the alternate pin configuration is as follows: ? oc0b/pcint15 ? port b, bit 7 oc0b, output compare match b output: the pb7 pi n can serve as an external output for the timer/counter0 output compare. the pin has to be configured as an output (ddb7 set (one)) to serve this function. the oc0b pin is also th e output pin for the pwm mode timer function. pcint15, pin change interrupt source 15. the pb 7 pin can serve as external interrupt source to the mcu. ? oc0a/pcint14 ? port b, bit 6 oc0a, output compare match a output: the pb6 pi n can serve as an external output for the timer/counter0 output compare. the pin has to be configured as an output (ddb6 set (one)) to serve this function. the oc0a pin is also th e output pin for the pwm mode timer function. pcint14, pin change interrupt source 14. the pb 6 pin can serve as external interrupt source to the mcu. ? pcint13:12 ? port b, bit 5:4 pcint13 - pcint12, pin change interrupt source 13:12. the pb5:4 pins can serve as external interrupt sources to the mcu. ? tck/pcint11 ? po rt b, bit 3 tck, jtag test clock: jtag operation is synchronous to tck. when the jtag interface is enabled, this pin can not be used as an i/o pin. pcint11, pin change interrupt source 11. the pb 3 pin can serve as external interrupt source to the mcu. table 13-6. port b pins alternate functions port pin alternate functions pb7 oc0b (output compare and pwm output b for timer/counter0) pcint15 (pin change interrupt 15) pb6 oc0a (output compare and pwm output a for timer/counter0) pcint14 (pin change interrupt 14) pb5 pcint13 (pin change interrupt 13) pb4 pcint12 (pin change interrupt 12) pb3 tck (jtag test clock) pcint11 (pin change interrupt 11) pb2 tms (jtag test mode select) pcint10 (pin change interrupt 10) pb1 tdi (jtag test data input/) pcint9 (pin change interrupt 9) pb0 tdo (jtag test data output) pcint8 (pin change interrupt 8)
71 2548f?avr?03/2013 atmega406 ? tms/pcint10 ? port b, bit 2 tms, jtag test mode select: this pin is used for navigating through the tap-controller state machine. when the jtag interface is enabled, this pin can not be used as an i/o pin. pcint10, pin change interrupt source 10. the pb 2 pin can serve as external interrupt source to the mcu. ? tdi/pcint9 ? port b, bit 1 tdi, jtag test data input: serial input data to be shifted in the instruction register or data register (scan chains). when the jtag interface is enabled, this pin can not be used as i/o pin. pcint9, pin change interrupt source 9. the pb1 pin can serve as external interrupt source to the mcu. ? tdo/pcint8 ? po rt b, bit 0 tdo, jtag test data output: se rial output data from instruction register or data register. when the jtag interface is enabled, this pin can not be used as an i/o pin. pcint8, pin change interrupt source 8. the pb0 pin can serve as external interrupt source to the mcu. table 13-7 and table 13-8 relate the alternate functions of port b to the overriding signals shown in figure 13-5 on page 66 . table 13-7. overriding signals for alte rnate functions in pb7:pb4 signal name pb7/ocob/ pcint15 pb6/ocoa/ pcint14 pb5/ pcint13 pb4/ pcint12 puoe0000 puov0000 ddoe 0 0 0 0 ddov 0 0 0 0 pvoe oc0b enable oc0a enable 0 pvov oc0b oc0a 0 ptoe???? dieoe0000 dieov0000 di pcint15 input pcint14 input pcint13 input pcint12 input aio????
72 2548f?avr?03/2013 atmega406 . 13.3.3 alternate functions of port d the port d pins with alternate functions are shown in table 13-9 . the alternate pin configuration is as follows: ? t0 ? port b, bit 0 t0, timer/counter0 counter source. table 13-10 on page 73 relates the alternate functions of port d to the overriding signals shown in figure 13-5 on page 66 . table 13-8. overriding signals for alte rnate functions in pb3:pb0 signal name pb3/tck/ pcint11 pb2/tms/ pcint10 pb1/tdi/ pcint9 pb0/tdo/ pcint8 puoe jtagen jtagen jtagen jtagen puov1110 ddoe jtagen jtagen jtagen jtagen ddov000shift_ir + shift_dr pvoe000jtagen pvov000tdo ptoe???? dieoe jtagen jtagen jtagen jtagen dieov0000 di tck/pcint11 input tms/pcint10 input tdi/pcint9 input pcint8 input aio???? table 13-9. port d pins alternate functions port pin alternate function pd0 t0 (timer/counter0 clock input)
73 2548f?avr?03/2013 atmega406 13.4 register description 13.4.1 mcucr ? mcu control register ? bit 4 ? pud: pull-up disable when this bit is written to one, the pull-ups in the i/o ports are disabled even if the ddxn and portxn registers are configured to enable the pull-ups ({ddxn, portxn} = 0b01). see ?con- figuring the pin? on page 61 for more details about this feature. 13.4.2 porta ? port a data register 13.4.3 ddra ? port a da ta direction register 13.4.4 pina ? port a input pins address table 13-10. overriding signals for alte rnate functions in pd1:pd0 signal name pd1 pd0/t0 puoe 0 0 puov 0 0 ddoe 0 0 ddov 0 0 pvoe 0 pvov 0 ptoe ? ? dieoe 0 0 dieov 0 0 di ? t0 input aio ? ? bit 7 6 5 4 3 2 1 0 0x35 (0x55) jtd ? ?pud ? ? ivsel ivce mcucr read/write r/w r r r/w r r r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x02 (0x22) porta7 porta6 porta5 porta4 porta3 porta2 porta1 porta0 porta read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x01 (0x21) dda7 dda6 dda5 dda4 dda3 dda2 dda1 dda0 ddra read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x00 (0x20) pina7 pina6 pina5 pina4 pina3 pina2 pina1 pina0 pina read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value n/a n/a n /a n/a n/a n/a n/a n/a
74 2548f?avr?03/2013 atmega406 13.4.5 portb ? port b data register 13.4.6 ddrb ? port b da ta direction register 13.4.7 pinb ? port b input pins address 13.4.8 portd ? port d data register 13.4.9 ddrd ? port d da ta direction register 13.4.10 pind ? port d input pins address bit 76543210 0x05 (0x25) portb7 portb6 portb5 portb4 portb3 portb2 portb1 portb0 portb read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x04 (0x24) ddb7 ddb6 ddb5 ddb4 ddb3 ddb2 ddb1 ddb0 ddrb read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x03 (0x23) pinb7 pinb6 pinb5 pinb4 pinb3 pi nb2 pinb1 pinb0 pinb read/writerrrrrrrr initial value n/a n/a n /a n/a n/a n/a n/a n/a bit 76543210 0x0b (0x2b) ??????portd1portd0portd read/writerrrrrrr/wr/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x0a (0x2a) ???? ?? ddd1 ddd0 ddrd read/writerrrrrrr/wr/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x09 (0x29) ???? ?? pind1 pind0 pind read/writerrrrrrr/wr/w initial value 0 0 0 0 0 0 n/a n/a
75 2548f?avr?03/2013 atmega406 14. high voltage i/o ports all high voltage avr ports have true read-modif y-write functionality when used as general dig- ital i/o ports. this means that the state of one port pin can be changed without unintentionally changing the state of any other pin with the sbi and cbi instructions. all high voltage i/o pins have protection zener diodes to ground as indicated in figure 14-1 . see ?electrical characteris- tics? on page 225 for a complete lis t of parameters. figure 14-1. high voltage i/o pin equivalent schematic all registers and bit references in this section are written in general form. a lower case ?x? repre- sents the numbering letter for the port, and a lower case ?n? represents the bit number. however, when using the register or bit defines in a progr am, the precise form must be used. for example, portc3 for bit number three in port c, here documented generally as portxn. the physical i/o registers and bit locations are listed in ?register description for high voltage output ports? on page 76 . one i/o memory address location is allocated for each high voltage port, the data register ? portx. the data register is read/write. using the i/o port as general dig ital output is described in ?high voltage ports as general dig- ital outputs? on page 75 . 14.1 high voltage ports as general digital outputs the high voltage ports are high voltage tolerant open collector output ports. figure 14-2 shows a functional description of one output po rt pin, here generically called pxn. c pin logic see figure "general high voltage digital i/o" for details pxn
76 2548f?avr?03/2013 atmega406 figure 14-2. general high voltage digital i/o (1) note: 1. wrx and rrx are common to all pins within the same port. 14.2 configuring the pin each port pin has one register bit: portxn. as shown in ?register description for high voltage output ports? on page 76 , the portxn bits are accessed at the portx i/o address. if portxn is written logic one, the port pin is driven low (zer o). if portxn is written logic zero, the port pin is tri-stated. the port pins are tri-stated when a reset condition becomes active, even if no clocks are running. 14.3 register description for hi gh voltage output ports 14.3.1 portc ? port c data register rrx wrx wrx: write portx rrx: read portx register reset q q d clr portxn dat a bus pxn bit 76543210 0x08 (0x28) ? portc0 portc read/writerrrrrrrr/w initial value 0 0 0 0 0 0 0 0
77 2548f?avr?03/2013 atmega406 15. 8-bit timer/counter0 with pwm timer/counter0 is a general purpose 8-bit time r/counter module, with two independent output compare units, and with pwm support. it allows accurate program execution timing (event man- agement) and wave generation. the main features are: ? two independent output compare units ? double buffered output compare registers ? clear timer on compare match (auto reload) ? glitch free, phase correct pulse width modulator (pwm) ? variable pwm period ? frequency generator ? three independent interrupt sources (tov0, ocf0a, and ocf0b) 15.1 overview a simplified block diagram of the 8-bit timer/counter is shown in figure 15-1 . for the actual placement of i/o pins, refer to ?pinout atmega406.? on page 2 . cpu accessible i/o registers, including i/o bits and i/o pins, are shown in bold. the device-specific i/o register and bit loca- tions are listed in the ?8-bit timer/counter register description? on page 88 . the prtim0 bit in ?prr0 ? power reduction register 0? on page 36 must be written to zero to enable timer/counter0 module. figure 15-1. 8-bit timer/counter block diagram 15.1.1 definitions many register and bit references in this section are written in general form. a lower case ?n? replaces the timer/counter number, in this case 0. a lower case ?x? replaces the output com- pare unit, in this case compare unit a or comp are unit b. however, when using the register or bit defines in a program, the precise form must be used, i.e., tcnt0 for accessing timer/counter0 counter value and so on. timer/counter data b u s ocrna ocrnb = = tcntn waveform generation waveform generation ocna ocnb = fixed top value control logic = 0 top bottom count clear direction tovn (int.req.) ocna (int.req.) ocnb (int.req.) tccrna tccrnb clk tn prescaler t/c oscillator clk i/o tosc1 tosc2
78 2548f?avr?03/2013 atmega406 the definitions in table 15-1 are also used extensively throughout the document. 15.1.2 registers the timer/counter (tcnt0) and output compare registers (ocr0a and ocr0b) are 8-bit registers. interrupt request (abbreviated to int.req . in the figure) signals are all visible in the timer interrupt flag register (t ifr0). all interrupts are individually masked with the timer inter- rupt mask register (timsk0). tifr0 and timsk0 are not shown in the figure. the timer/counter can be clocked internally, via th e prescaler, or by an external clock source on the t0 pin. the clock select logic block contro ls which clock source and edge the timer/counter uses to increment (or decrement) its value. th e timer/counter is inactive when no clock source is selected. the output from th e clock select logic is referred to as the timer clock (clk t0 ). the double buffered output compare register s (ocr0a and ocr0b) are compared with the timer/counter value at all times. the result of the compare can be used by the waveform gen- erator to generate a pwm or variable frequency output on the output compare pins (oc0a and oc0b). see section ?15.4.3? on page 80. for details. the compare ma tch event will also set the compare flag (ocf0a or ocf0b) which can be us ed to generate an output compare interrupt request. 15.2 timer/counter clock sources the timer/counter can be clocked by an internal or an external clock source. the clock source is selected by the clock select logic which is controlled by the clock select (cs02:0) bits located in the timer/counter control register (tccr0b). for details on clock sources and pres- caler, see ?timer/counter0 and timer/counter1 prescalers? on page 103 . 15.3 counter unit the main part of the 8-bit timer/counter is the programmable bi-directional counter unit. figure 15-2 shows a block diagram of the counter and its surroundings. figure 15-2. counter unit block diagram signal description (internal signals): table 15-1. definitions bottom the counter reaches the bottom when it becomes 0x00. max the counter reaches its maximum w hen it becomes 0xff (decimal 255). top the counter reaches the top when it be comes equal to the highest value in the count sequence. the top value can be assigned to be the fixed value 0xff (max) or the value stored in the ocr0a register. the assignment is depen- dent on the mode of operation. data b u s tcntn control logic count tovn (int.req.) clock select top tn edge detector ( from prescaler ) clk tn bottom direction clear
79 2548f?avr?03/2013 atmega406 count increment or decrement tcnt0 by 1. direction select between increment and decrement. clear clear tcnt0 (set all bits to zero). clk t n timer/counter clock, referred to as clk t0 in the following. top signalize that tcnt0 has reached maximum value. bottom signalize that tcnt0 has re ached minimum value (zero). depending of the mode of operation used, the counter is cleared, incremented, or decremented at each timer clock (clk t0 ). clk t0 can be generated from an external or internal clock source, selected by the clock select bits (cs02:0). w hen no clock source is selected (cs02:0 = 0) the timer is stopped. however, the tcnt0 value can be accessed by the cpu, regardless of whether clk t0 is present or not. a cpu write overrides (has priority over) all counter clear or count operations. the counting sequence is determined by the se tting of the wgm01 and wgm00 bits located in the timer/counter control regist er (tccr0a) and the wgm02 bit located in the timer/counter control register b (tccr0b). there are clos e connections between how the counter behaves (counts) and how waveforms are generated on th e output compare outputs oc0a and oc0b. for more details about advanced counting sequences and waveform generation, see ?modes of operation? on page 82 . the timer/counter overflow flag (tov0) is set a ccording to the mode of operation selected by the wgm02:0 bits. tov0 can be us ed for generating a cpu interrupt. 15.4 output compare unit the 8-bit comparator continuously compares tcnt0 with the output compare registers (ocr0a and ocr0b). whenever tcnt0 equals ocr0 a or ocr0b, the comparator signals a match. a match will set the output compare flag (ocf0a or ocf0 b) at the next timer clock cycle. if the corresponding interrupt is enabled, the output compare flag generates an output compare interrupt. the output compare flag is aut omatically cleared when the interrupt is exe- cuted. alternatively, the flag can be cleared by software by writing a logical one to its i/o bit location. the waveform generator uses the matc h signal to generate an output according to operating mode set by the wgm02:0 bits and compare output mode (com0x1:0) bits. the max and bottom signals are used by the waveform generator for handling the special cases of the extreme values in some modes of operation ( ?modes of operation? on page 82 ). figure 15-3 shows a block diagram of the output compare unit.
80 2548f?avr?03/2013 atmega406 figure 15-3. output compare unit, block diagram the ocr0x registers are double buffered when using any of the pulse width modulation (pwm) modes. for the normal and clear timer on compare (ctc) modes of operation, the dou- ble buffering is disabled. the double buffering synchronizes the update of the ocr0x compare registers to either top or bottom of the counting sequence. the synchronization prevents the occurrence of odd-length, non-symmetrical pwm pulses, thereby making the output glitch-free. the ocr0x register access may seem complex, but this is not case. when the double buffering is enabled, the cpu has access to the ocr0x buffer register, and if double buffering is dis- abled the cpu will access the ocr0x directly. 15.4.1 force output compare in non-pwm waveform generation modes, the matc h output of the comparator can be forced by writing a one to the force outp ut compare (foc0x) bit. forci ng compare match will not set the ocf0x flag or reload/clear the timer, but the oc0x pin will be updated as if a real compare match had occurred (the com0x1:0 bits settings de fine whether the oc0x pin is set, cleared or toggled). 15.4.2 compare match blocking by tcnt0 write all cpu write operations to th e tcnt0 register will block any co mpare match that occur in the next timer clock cycle, even when the timer is stopped. this feat ure allows ocr0x to be initial- ized to the same value as tcnt0 without trigge ring an interrupt when the timer/counter clock is enabled. 15.4.3 using the output compare unit since writing tcnt0 in any mode of operation will block all comp are matches for one timer clock cycle, there are risks involved when changing tc nt0 when using the output compare unit, independently of whether the time r/counter is running or not. if the value written to tcnt0 equals the ocr0x value, the compare match will be missed, resulting in incorrect waveform generation. similarly, do not write the tcnt0 value equal to bottom when the counter is downcounting. the setup of the oc0x should be performed before setting the data direction register for the port pin to output. the easiest way of setting the oc0x value is to use the force output com- ocfn x (int.req.) = (8-bit comparator ) ocrnx ocnx data bus tcntn wgmn1:0 waveform generator top focn comnx1:0 bottom
81 2548f?avr?03/2013 atmega406 pare (foc0x) strobe bits in normal mode. the oc0x registers keep their values even when changing between waveform generation modes. be aware that the com0x1:0 bits are not doubl e buffered together with the compare value. changing the com0x1:0 bits will take effect immediately. 15.5 compare match output unit the compare output mode (com0x1:0) bits ha ve two functions. the waveform generator uses the com0x1:0 bits for defining the output co mpare (oc0x) state at the next compare match. also, the com0x1:0 bits contro l the oc0x pin output source. figure 15-4 shows a simplified schematic of the logic affected by the com0x1:0 bit setting. the i/o registers, i/o bits, and i/o pins in the figure are shown in bold. only the parts of the general i/o port control registers (ddr and port) that are affected by the com0x1:0 bits are shown. when referring to the oc0x state, the reference is for the internal oc0x re gister, not the oc0x pin. if a system reset occur, the oc0x register is reset to ?0?. figure 15-4. compare match output unit, schematic the general i/o port function is overridden by the output compare (oc0x) from the waveform generator if either of the com0x1:0 bits are se t. however, the oc0x pin direction (input or out- put) is still controlled by the da ta direction register (ddr) for th e port pin. the data direction register bit for the oc0x pin (ddr_oc0x) must be set as output before th e oc0x value is visi- ble on the pin. the port over ride function is independent of the waveform generation mode. the design of the output compare pin logic allows initialization of the oc 0x state before the out- put is enabled. note that some com0x1:0 bi t settings are reserved for certain modes of operation. see section ?15.8? on page 88. 15.5.1 compare output mode and waveform generation the waveform generator uses the com0x1:0 bits differently in normal, ctc, and pwm modes. for all modes, setting the com0x1:0 = 0 tell s the waveform generator that no action on the oc0x register is to be performed on the next compare match. for compare output actions in the non-pwm modes refer to table 15-2 on page 88 . for fast pwm mode, refer to table 15-3 on page 88 , and for phase correct pwm refer to table 15-4 on page 89 . port ddr dq dq ocnx pin ocnx dq waveform generator comnx1 comnx0 0 1 data bus focn clk i/o
82 2548f?avr?03/2013 atmega406 a change of the com0x1:0 bits st ate will have effect at the first compare match after the bits are written. for non-pwm modes, the action can be fo rced to have immediate effect by using the foc0x strobe bits. 15.6 modes of operation the mode of operation, i.e., t he behavior of the timer/counter and the output compare pins, is defined by the combination of the waveform generation mode (wgm02:0) and compare output mode (com0x1:0) bits. the compare output mode bits do not affect the counting sequence, while the waveform generation mode bits do. the com0x1:0 bits control whether the pwm out- put generated should be inverted or not (inverted or non-inverted pwm). for non-pwm modes the com0x1:0 bits control whethe r the output should be set, cleared, or toggled at a compare match ( see section ?15.5? on page 81. ). for detailed timing information refer to ?timer/counter timing diagrams? on page 86 . 15.6.1 normal mode the simplest mode of operation is the normal mode (wgm02:0 = 0). in this mode the counting direction is always up (incre menting), and no counter clear is performed. the counter simply overruns when it passes its maxi mum 8-bit value (top = 0xff) and then restarts from the bot- tom (0x00). in normal o peration the timer/counter overflow flag (tov0) will be set in the same timer clock cycle as the tcnt0 becomes zero. the tov0 flag in this case behaves like a ninth bit, except that it is only set, not cleared. ho wever, combined with the timer overflow interrupt that automatically clears the tov0 flag, the timer resolution can be increased by software. there are no special cases to consider in the normal mode, a new counter value can be written anytime. the output compare unit can be used to generate interrupts at some given time. using the out- put compare to generate waveforms in normal mode is not recommended, since this will occupy too much of the cpu time. 15.6.2 clear timer on compare match (ctc) mode in clear timer on compare or ctc mode (wgm 02:0 = 2), the ocr0a register is used to manipulate the counter resolution . in ctc mode the counter is cleared to zero when the counter value (tcnt0) matches the ocr0a. the ocr0a de fines the top value fo r the counter, hence also its resolution. this mode allows greater control of the compare match output frequency. it also simplifies the operation of counting external events. the timing diagram for the ctc mode is shown in figure 15-5 . the counter value (tcnt0) increases until a compare match occurs between tcnt0 and o cr0a, and then counter (tcnt0) is cleared.
83 2548f?avr?03/2013 atmega406 figure 15-5. ctc mode, timing diagram an interrupt can be generated each time the c ounter value reaches the top value by using the ocf0a flag. if the interrupt is enabled, the interrupt handler routine can be used for updating the top value. however, changing top to a va lue close to bottom when the counter is run- ning with none or a low prescaler value must be done with care since the ctc mode does not have the double buffering feature. if the new value written to ocr0a is lower than the current value of tcnt0, the counter will miss the compar e match. the counter will then have to count to its maximum value (0xff) and wrap around starting at 0x00 before the compare match can occur. for generating a waveform output in ctc mode, t he oc0a output can be set to toggle its logical level on each compare match by setting the compare output mode bits to toggle mode (com0a1:0 = 1). the oc0a value will not be visible on the port pin unless the data direction for the pin is set to output. the waveform ge nerated will have a ma ximum frequency of f oc0 = f clk_i/o /2 when ocr0a is set to zero (0x00). the waveform frequency is defined by the following equation: the n variable represents the prescale factor (1, 8, 64, 256, or 1024). as for the normal mode of operat ion, the tov0 flag is set in the same timer clock cycle that the counter counts fr om max to 0x00. 15.6.3 fast pwm mode the fast pulse width modulation or fast pwm mode (wgm02:0 = 3 or 7) provides a high fre- quency pwm waveform generation option. the fa st pwm differs from the other pwm option by its single-slope operation. the c ounter counts from bottom to top then restarts from bot- tom. top is defined as 0xff when wgm2:0 = 3, and ocr0a when wgm2:0 = 7. in non- inverting compare output mode, the output compare (oc0x) is cleared on the compare match between tcnt0 and ocr0x, and set at bottom. in inverting compare output mode, the out- put is set on compare match and cleared at bottom. due to the single-slope operation, the operating frequency of the fast pwm mode can be twice as high as the phase correct pwm mode that use dual-slope operation. this high frequency makes the fast pwm mode well suited for power regulation, rectification, and dac app lications. high frequency a llows physically small sized external components (coils, capacitors), and therefore reduces total system cost. in fast pwm mode, the counter is incremented until the counter value matches the top value. the counter is then cleared at the following timer clock cycle. the timing diagram for the fast tcntn ocn (toggle) ocnx interrupt flag set 1 4 period 2 3 (comnx1:0 = 1) f ocnx f clk_i/o 2 n 1 ocrnx + ?? ?? ------------------------------------------------- - =
84 2548f?avr?03/2013 atmega406 pwm mode is shown in figure 15-6 . the tcnt0 value is in the timing diagram shown as a his- togram for illustrating the single-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt0 slopes represent compare matches between ocr0x and tcnt0. figure 15-6. fast pwm mode, timing diagram the timer/counter overflow flag (tov0) is set each time the counter re aches top. if the inter- rupt is enabled, the interrupt handler routi ne can be used for updating the compare value. in fast pwm mode, the compare unit allows generation of pwm waveforms on the oc0x pins. setting the com0x1:0 bits to two will produce a non-inverted pwm and an inverted pwm output can be generated by setting the com0x1:0 to th ree: setting the com0a1:0 bits to one allows the oc0a pin to toggle on compare matches if th e wgm02 bit is set. this option is not available for the oc0b pin (see table 15-6 on page 89 ). the actual oc0x value will only be visible on the port pin if the data direction fo r the port pin is set as output. the pwm waveform is generated by setting (or clearing) the oc0x register at the compare match between ocr0x and tcnt0, and clearing (or setting) the oc0x r egister at the timer clock c ycle the counter is cleared (changes from top to bottom). the pwm frequency for the output can be calculated by the following equation: the n variable represents the prescale factor (1, 8, 64, 256, or 1024). the extreme values for the ocr0a register represents special cases when generating a pwm waveform output in the fast pwm mode. if t he ocr0a is set equal to bottom, the output will be a narrow spike for each max+1 timer clock cycle. setting the ocr0a equal to max will result in a constantly high or low output (depending on the polarity of the out put set by the com0a1:0 bits.) a frequency (with 50% duty cycle) waveform out put in fast pwm mode can be achieved by set- ting oc0x to toggle its logical level on each compare match (com0x1:0 = 1). the waveform generated will have a maximum frequency of f oc0 = f clk_i/o /2 when ocr0a is set to zero. this tcntn ocrnx update and tovn interrupt flag set 1 period 2 3 ocn ocn (comnx1:0 = 2) (comnx1:0 = 3) ocrnx interrupt flag set 4 5 6 7 f ocnxpwm f clk_i/o n 256 ? ------------------ =
85 2548f?avr?03/2013 atmega406 feature is similar to the oc0a toggle in ctc mo de, except the double buff er feature of the out- put compare unit is enabled in the fast pwm mode. 15.6.4 phase correct pwm mode the phase correct pwm mode (wgm02:0 = 1 or 5) provides a high resolution phase correct pwm waveform generation option. the phase correct pwm mode is based on a dual-slope operation. the counter counts repeatedly from bottom to top and then from top to bot- tom. top is defined as 0xff when wgm2:0 = 1, and ocr0a when wgm2:0 = 5. in non- inverting compare output mode, the output compare (oc0x) is cleared on the compare match between tcnt0 and ocr0x while upcounting, and set on the compare match while downcount- ing. in inverting output compare mode, the operation is inverted. the dual-slope operation has lower maximum operation frequency than single slope operation. however, due to the symmet- ric feature of the dual-slope pwm modes, these modes are preferred for motor control applications. in phase correct pwm mode the counter is incremented until the counter value matches top. when the counter reaches top, it changes the count direction. the tcnt0 value will be equal to top for one timer clock cycle. the timing diagram for the phase correct pwm mode is shown on figure 15-7 . the tcnt0 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt0 sl opes represent compare matches between ocr0x and tcnt0. figure 15-7. phase correct pwm mode, timing diagram the timer/counter overflow flag (tov0) is set each time the counter reaches bottom. the interrupt flag can be used to g enerate an interrupt each time the counter reaches the bottom value. in phase correct pwm mode, the compare unit allows generation of pwm waveforms on the oc0x pins. setting the com0x1:0 bits to two will produce a non-inverted pwm. an inverted pwm output can be generated by setting the com0x1:0 to three: setting the com0a0 bits to tovn interrupt flag set ocnx interrupt flag set 1 2 3 tcntn period ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3) ocrnx update
86 2548f?avr?03/2013 atmega406 one allows the oc0a pin to toggle on compare ma tches if the wgm02 bit is set. this option is not available for the oc0b pin (see table 15-7 on page 90 ). the actual oc0x value will only be visible on the port pin if the data direction for the port pin is set as output. the pwm waveform is generated by clearing (or setting) the oc0x re gister at the compare match between ocr0x and tcnt0 when the counter increments, and setting (or clearing) the oc0x register at compare match between ocr0x and tcnt0 when the counter decrements. the pwm frequency for the output when using phase correct pwm can be calculated by the following equation: the n variable represents the prescale factor (1, 8, 64, 256, or 1024). the extreme values for the ocr0a register represent special cases when generating a pwm waveform output in the phase correct pwm mo de. if the ocr0a is set equal to bottom, the output will be continuously low an d if set equal to max the output will be continuously high for non-inverted pwm mode. for in verted pwm the output will have the opposite logic values. at the very start of period 2 in figure 15-7 ocnx has a transition from high to low even though there is no compare match. the point of this transition is to guarantee symmetry around bot- tom. there are two cases that give a transition without compare match. ? ocrnx changes its value from max, like in figure 15-7 . when the ocr0a value is max the ocn pin value is the same as the result of a down-counting compare match. to ensure symmetry around bottom the ocnx value at max must correspond to the result of an up- counting compare match. ? the timer starts counting from a value higher than the one in ocrnx, and for that reason misses the compare match and hence the ocnx change that would have happened on the way up. 15.7 timer/counter timing diagrams the timer/counter is a synchronous design and the timer clock (clk t0 ) is therefore shown as a clock enable signal in the following figures. the figures include information on when interrupt flags are set. figure 15-8 contains timing data for basic timer/counter operation. the figure shows the count sequence close to the max value in all modes other than phase correct pwm mode. figure 15-8. timer/counter timing diagram, no prescaling figure 15-9 shows the same timing data, but with the prescaler enabled. f ocnxpcpwm f clk_i/o n 510 ? ------------------ = clk tn (clk i/o /1) tovn clk i/o tcntn max - 1 max bottom bottom + 1
87 2548f?avr?03/2013 atmega406 figure 15-9. timer/counter timing diagram, with prescaler (f clk_i/o /8) figure 15-10 shows the setting of ocf0b in all mo des and ocf0a in all modes except ctc mode and pwm mode, where ocr0a is top. figure 15-10. timer/counter timing diagram, setting of ocf0x, with prescaler (f clk_i/o /8) figure 15-11 shows the setting of ocf0a and the clearing of tcnt0 in ctc mode and fast pwm mode where ocr0a is top. figure 15-11. timer/counter timing diagram, clear timer on compare match mode, with pres- caler (f clk_i/o /8) tovn tcntn max - 1 max bottom bottom + 1 clk i/o clk tn (clk i/o /8) ocfnx ocrnx tcntn ocrnx value ocrnx - 1 ocrnx ocrnx + 1 ocrnx + 2 clk i/o clk tn (clk i/o /8) ocfnx ocrnx tcntn (ctc) top top - 1 top bottom bottom + 1 clk i/o clk tn (clk i/o /8)
88 2548f?avr?03/2013 atmega406 15.8 8-bit timer/counter register description 15.8.1 tccr0a ? timer/coun ter control register a ? bits 7:6 ? com0a1:0: compare match output a mode these bits control the output compare pin (oc0a) behavior. if one or both of the com0a1:0 bits are set, the oc0a output overrides the normal po rt functionality of the i/o pin it is connected to. however, note that the data direction r egister (ddr) bit corresponding to the oc0a pin must be set in order to enable the output driver. when oc0a is connected to the pin, the function of the com0a1:0 bits depends on the wgm02:0 bit setting. table 15-2 shows the com0a1:0 bit func tionality when the wgm02:0 bits are set to a normal or ctc mode (non-pwm). table 15-3 shows the com0a1:0 bit functionality when the wgm01:0 bits are set to fast pwm mode. note: 1. a special case occurs when ocr0a equals top and com0a1 is set. in this case, the com- pare match is ignored, but the se t or clear is done at top. see ?fast pwm mode? on page 83 for more details. bit 7 6 5 4 3 2 1 0 0x24 (0x44) com0a1 com0a0 com0b1 com0b0 ? ? wgm01 wgm00 tccr0a read/write r/w r/w r/w r/w r r r/w r/w initial value 0 0 0 0 0 0 0 0 table 15-2. compare output mode, non-pwm mode com0a1 com0a0 description 0 0 normal port operation, oc0a disconnected. 0 1 toggle oc0a on compare match 1 0 clear oc0a on compare match 1 1 set oc0a on compare match table 15-3. compare output mode, fast pwm mode (1) com0a1 com0a0 description 0 0 normal port operation, oc0a disconnected. 01 wgm02 = 0: normal port operation, oc0a disconnected. wgm02 = 1: toggle oc0a on compare match. 1 0 clear oc0a on compare match, set oc0a at top 1 1 set oc0a on compare match, clear oc0a at top
89 2548f?avr?03/2013 atmega406 table 15-4 shows the com0a1:0 bit functionality when the wgm02:0 bits are set to phase cor- rect pwm mode. note: 1. a special case occurs when ocr0a equals top and com0a1 is set. in this case, the com- pare match is ignored, but the set or clear is done at top. see ?phase correct pwm mode? on page 85 for more details. ? bits 5:4 ? com0b1:0: compare match output b mode these bits control the output compare pin (oc0b) behavior. if one or both of the com0b1:0 bits are set, the oc0b output overrides the normal po rt functionality of the i/o pin it is connected to. however, note that the data direction r egister (ddr) bit corresponding to the oc0b pin must be set in order to enable the output driver. when oc0b is connected to the pin, the function of the com0b1:0 bits depends on the wgm02:0 bit setting. table 15-5 shows the com0b1:0 bit func tionality when the wgm02:0 bits are set to a normal or ctc mode (non-pwm). table 15-6 shows the com0b1:0 bit functionality when the wgm02:0 bits are set to fast pwm mode. note: 1. a special case occurs when ocr0b equals top and com0b1 is set. in this case, the com- pare match is ignored, but the se t or clear is done at top. see ?fast pwm mode? on page 83 for more details. table 15-4. compare output mode, phase correct pwm mode (1) com0a1 com0a0 description 0 0 normal port operation, oc0a disconnected. 01 wgm02 = 0: normal port oper ation, oc0a disconnected. wgm02 = 1: toggle oc0a on compare match. 10 clear oc0a on compare match when up-counting. set oc0a on compare match when down-counting. 11 set oc0a on compare match when up-counting. clear oc0a on compare match when down-counting. table 15-5. compare output mode, non-pwm mode com0b1 com0b0 description 0 0 normal port operation, oc0b disconnected. 0 1 toggle oc0b on compare match 1 0 clear oc0b on compare match 1 1 set oc0b on compare match table 15-6. compare output mode, fast pwm mode (1) com0b1 com0b0 description 0 0 normal port operation, oc0b disconnected. 01reserved 1 0 clear oc0b on compare match, set oc0b at top 1 1 set oc0b on compare match, clear oc0b at top
90 2548f?avr?03/2013 atmega406 table 15-7 shows the com0b1:0 bit functionality when the wgm02:0 bits are set to phase cor- rect pwm mode. note: 1. a special case occurs when ocr0b equals top and com0b1 is set. in this case, the com- pare match is ignored, but the set or clear is done at top. see ?phase correct pwm mode? on page 85 for more details. ? bits 3, 2 ? res: reserved bits these bits are reserved bits in the atmega406 and will always read as zero. ? bits 1:0 ? wgm01:0: waveform generation mode combined with the wgm02 bit found in the tccr0b register, these bits control the counting sequence of the counter, the source for maximu m (top) counter value, and what type of wave- form generation to be used, see table 15-8 . modes of operation supported by the timer/counter unit are: normal mode (counter), clear time r on compare match (ctc) mode, and two types of pulse width modulation (pwm) modes (see ?modes of operation? on page 82 ). notes: 1. max = 0xff 2. bottom = 0x00 table 15-7. compare output mode, phase correct pwm mode (1) com0b1 com0b0 description 0 0 normal port operation, oc0b disconnected. 01reserved 10 clear oc0b on compare match when up-counting. set oc0b on compare match when down-counting. 11 set oc0b on compare match when up-counting. clear oc0b on compare match when down-counting. table 15-8. waveform generation mode bit description mode wgm02 wgm01 wgm00 timer/counter mode of operation top update of ocrx at tov flag set on (1)(2) 0 0 0 0 normal 0xff immediate max 1 0 0 1 pwm, phase correct 0xff top bottom 2 0 1 0 ctc ocra immediate max 3 0 1 1 fast pwm 0xff top max 4 1 0 0 reserved ? ? ? 5 1 0 1 pwm, phase correct ocra top bottom 6 1 1 0 reserved ? ? ? 7 1 1 1 fast pwm ocra top top
91 2548f?avr?03/2013 atmega406 15.8.2 tccr0b ? timer/coun ter control register b ? bit 7 ? foc0a: force output compare a the foc0a bit is only active when the wgm bits specify a non-pwm mode. however, for ensuring compatibility with future devices, this bit must be set to zero when tccr0b is written when operating in pwm mode. when writing a logical one to the foc0a bit, an immediate compare match is forced on the wa veform generation unit . the oc0a output is changed according to its com0a1:0 bits setting. note that the foc0a bit is implemented as a strobe. therefore it is the value present in the com0a1:0 bits that determines the effect of the forced compare. a foc0a strobe will not generate any interrupt, nor will it clear the timer in ctc mode using ocr0a as top. the foc0a bit is always read as zero. ? bit 6 ? foc0b: force output compare b the foc0b bit is only active when the wgm bits specify a non-pwm mode. however, for ensuring compatibility with future devices, this bit must be set to zero when tccr0b is written when operating in pwm mode. when writing a logical one to the foc0b bit, an immediate compare match is forced on the wa veform generation unit . the oc0b output is changed according to its com0b1:0 bits setting. note that the foc0b bit is implemented as a strobe. therefore it is the value present in the com0b1:0 bits that determines the effect of the forced compare. a foc0b strobe will not generate any interrupt, nor will it clear the timer in ctc mode using ocr0b as top. the foc0b bit is always read as zero. ? bits 5:4 ? res: reserved bits these bits are reserved bits in the atmega406 and will always read as zero. ? bit 3 ? wgm02: waveform generation mode see the description in the ?tccr0a ? timer/counter control register a? on page 88 . ? bits 2:0 ? cs02:0: clock select the three clock select bits select the cloc k source to be used by the timer/counter. bit 7 6 5 4 3 2 1 0 0x25 (0x45) foc0a foc0b ? ? wgm02 cs02 cs01 cs00 tccr0b read/write w w r r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
92 2548f?avr?03/2013 atmega406 if external pin modes are used for the timer/counter0, transitions on the t0 pin will clock the counter even if the pin is configured as an outpu t. this feature allows software control of the counting. 15.8.3 tcnt0 ? timer/counter register the timer/counter register gives direct ac cess, both for read and write operations, to the timer/counter unit 8-bit counter. writing to the tcnt0 register blocks (removes) the compare match on the following timer clock. modifying t he counter (tcnt0) while the counter is running, introduces a risk of missing a compare match between tcnt0 and the ocr0x registers. 15.8.4 ocr0a ? output compare register a the output compare register a contains an 8-bi t value that is conti nuously compared with the counter value (tcnt0). a match can be used to generate an output compare interrupt, or to generate a waveform output on the oc0a pin. 15.8.5 ocr0b ? output compare register b the output compare register b contains an 8-bi t value that is conti nuously compared with the counter value (tcnt0). a match can be used to generate an output compare interrupt, or to generate a waveform output on the oc0b pin. table 15-9. clock select bit description cs02 cs01 cs00 description 0 0 0 no clock source (timer/counter stopped) 001clk i/o /(no prescaling) 010clk i/o /8 (from prescaler) 011clk i/o /64 (from prescaler) 100clk i/o /256 (from prescaler) 101clk i/o /1024 (from prescaler) 1 1 0 external clock source on t0 pin. clock on falling edge. 1 1 1 external clock source on t0 pin. clock on rising edge. bit 76543210 0x26 (0x46) tcnt0[7:0] tcnt0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x27 (0x47) ocr0a[7:0] ocr0a read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x28 (0x48) ocr0b[7:0] ocr0b read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
93 2548f?avr?03/2013 atmega406 15.8.6 timsk0 ? timer/counter interrupt mask register 0 ? bits 7:3 ? res: reserved bits these bits are reserved bits in the atmega406 and will always read as zero. ? bit 2 ? ocie0b: timer/counter output compare match b interrupt enable when the ocie0b bit is written to one, and the i-bit in the status register is set, the timer/counter compare match b interrupt is enab led. the corresponding interrupt is executed if a compare match in timer/counter occurs, i.e., when the ocf0b bi t is set in the timer/counter interrupt flag register ? tifr0. ? bit 1 ? ocie0a: timer/counter0 output compare match a interrupt enable when the ocie0a bit is written to one, and th e i-bit in the status register is set, the timer/counter0 compare match a interrupt is enabled. the corresponding interrupt is executed if a compare match in timer/counter0 occurs, i.e., when the ocf0a bit is set in the timer/counter 0 interrupt flag register ? tifr0. ? bit 0 ? toie0: timer/counter0 overflow interrupt enable when the toie0 bit is written to one, and t he i-bit in the status register is set, the timer/counter0 overflow interr upt is enabled. the corresponding interrupt is executed if an overflow in timer/counter0 occu rs, i.e., when the tov0 bit is set in the timer/counter 0 inter- rupt flag register ? tifr0. bit 7 6 5 4 3 2 1 0 (0x6e) ?????ocie0bocie0atoie0timsk0 read/write rrrrrr/wr/wr/w initial value 0 0 0 0 0 0 0 0
94 2548f?avr?03/2013 atmega406 15.8.7 tifr0 ? timer/counter 0 interrupt flag register ? bits 7:3 ? res: reserved bits these bits are reserved bits in the atmega406 and will always read as zero. ? bit 2 ? ocf0b: timer/counter 0 output compare b match flag the ocf0b bit is set when a compare match occurs between the timer/counter and the data in ocr0b ? output compare register0 b. ocf0b is cleared by hardware when executing the cor- responding interrupt handling vector. alternatively, ocf0b is cleared by writing a logic one to the flag. when the i-bit in sreg, ocie0b (tim er/counter compare b match interrupt enable), and ocf0b are set, the timer/counter compare match interrupt is executed. ? bit 1 ? ocf0a: timer/counter 0 output compare a match flag the ocf0a bit is set when a compare match oc curs between the timer/counter0 and the data in ocr0a ? output compare register0. ocf0a is cleared by hardware when executing the cor- responding interrupt handling vector. alternativel y, ocf0a is cleared by writing a logic one to the flag. when the i-bit in sreg, ocie0a (t imer/counter0 compare match interrupt enable), and ocf0a are set, the timer/counter0 co mpare match interrupt is executed. ? bit 0 ? tov0: timer/counter0 overflow flag the bit tov0 is set when an overflow occurs in timer/counter0. tov0 is cleared by hardware when executing the corresponding interrupt handling vector. alternatively, tov0 is cleared by writing a logic one to the flag. when the sreg i-bit, toie0 (timer/count er0 overflow interrupt enable), and tov0 are set, the timer/co unter0 overflow interrupt is executed. the setting of this flag is dependent of the wgm02:0 bit setting. refer to table 15-8 , ?waveform generation mode bit description? on page 90 . bit 76543210 0x15 (0x35) ?????ocf0bocf0atov0tifr0 read/write r r r r r r/w r/w r/w initial value 0 0 0 0 0 0 0 0
95 2548f?avr?03/2013 atmega406 16. 16-bit timer/counter1 the 16-bit timer/counter unit allows accurate program execution timing (event management). the main features are: ? one output compare unit ? clear timer on compare match (auto reload) ? two independent interrupt sources (tov1 and ocf1a) 16.1 overview most register and bit references in this document are written in general form. a lower case ?n? replaces the timer/counter number, and a lower case ?x? replaces the output compare unit channel. however, when using the register or bi t defines in a program, the precise form must be used, i.e., tcnt1 for accessing timer/counter1 counter value and so on. the physical i/o reg- ister and bit locations for atmega406 are listed in the ?16-bit timer/counter register description? on page 100 . a simplified block diagram of the 16 -bit timer/counter is shown in figure 16-1 . cpu accessible i/o registers, including i/o bits and i/o pins, are shown in bold. the prtim1 bit in ?prr0 ? power reduction register 0? on page 36 must be written to zero to enable timer/counter1 module. figure 16-1. 16-bit timer/counter block diagram 16.1.1 registers the timer/counter (tcnt1) and the output compare register (ocr1a) are both 16-bit regis- ters. special procedures must be followed w hen accessing the 16-bi t registers. these procedures are described in the section ?accessing 16-bit registers? on page 96 .the timer/counter control register (tccr1b) is an 8-bit register an has no cpu access restric- tions. interrupt requests (abbreviated to int.r eq. in the figure) signals are visible in the timer interrupt flag register (tifr). both interrupts are individually masked with the timer interrupt mask register (timsk). tifr and timsk are not shown in the figure. the timer/counter is clocked internally via the prescaler. the clock select logic block controls which clock source the timer/counter uses to in crement its value. the timer/counter is inactive when no clock source is selected. the output from the clock select logic is referred to as the timer clock (clk t 1 ). timer/counter d ata bus ocrna = tcntn =0xffff control logic count clear tovn (int.req .) tccrnb clk tn ocfna (int.req .)
96 2548f?avr?03/2013 atmega406 the output compare register (ocr1a) is compar ed with the timer/counter value at all time. the compare match event will set the compare matc h flag (ocf1a) which can be used to gen- erate an output compare interrupt request. 16.2 accessing 16-bit registers the tcnt1 and ocr1a are 16-bit registers that can be accessed by the avr cpu via the 8-bit data bus. the 16-bit register must be byte acce ssed using two read or write operations. each 16-bit timer has a single 8-bit register for tempor ary storing of the high byte of the 16-bit access. the same temporary register is shared between all 16-bit registers within each 16-bit timer. accessing the low byte triggers the 16-bit read or write operation. when the low byte of a 16-bit register is written by the cpu, the high byte stored in the temporary register, and the low byte written are both copied into the 16-bit register in the same clo ck cycle. when the low byte of a 16-bit register is read by the cpu, the high byte of the 16-bit register is copied into the temporary register in the same clock cycle as the low byte is read. not all 16-bit accesses uses the temporary regi ster for the high byte. reading the ocr1a 16-bit register does not involve using the temporary register. to do a 16-bit write, the high byte must be wr itten before the low byte . for a 16-bit read, the low byte must be read before the high byte . the following code examples show how to acce ss the 16-bit timer registers assuming that no interrupts updates the temporary register. the same principle can be used directly for accessing the ocr1a register. note that when using ?c?, the compiler handles the 16-bit access. note: 1. see ?about code examples? on page 7 . the assembly code example returns the t cnt1 value in the r17:r16 register pair. it is important to notice that accessing 16-bit registers are atomic operations. if an interrupt occurs between the two instructions accessing the 16-bit register, and the interrupt code assembly code examples (1) ... ; set tcnt 1 to 0x01ff ldi r17,0x01 ldi r16,0xff out tcnt 1 h,r17 out tcnt 1 l,r16 ; read tcnt 1 into r17:r16 in r16,tcnt 1 l in r17,tcnt 1 h ... c code examples (1) unsigned int i; ... /* set tcnt 1 to 0x01ff */ tcnt 1 = 0x1ff; /* read tcnt 1 into i */ i = tcnt 1 ; ...
97 2548f?avr?03/2013 atmega406 updates the temporary register by accessing the sa me or any other of the 16-bit timer registers, then the result of the access outside the interrupt will be corrupted. therefore, when both the main code and the interrupt code update the temporary register, the main code must disable the interrupts during the 16-bit access. the following code examples show how to do an atomic read of the tcnt1 register contents. reading the ocr1a register can be done using the same principle. note: 1. see ?about code examples? on page 7 . the assembly code example returns the t cnt1 value in the r17:r16 register pair. assembly code example (1) tim16_readtcnt 1 : ; save global interrupt flag in r18,sreg ; disable interrupts cli ; read tcnt 1 into r17:r16 in r16,tcnt 1 l in r17,tcnt 1 h ; restore global interrupt flag out sreg,r18 ret c code example (1) unsigned int tim16_readtcnt 1 ( void ) { unsigned char sreg; unsigned int i; /* save global interrupt flag */ sreg = sreg; /* disable interrupts */ _cli(); /* read tcnt 1 into i */ i = tcnt 1 ; /* restore global interrupt flag */ sreg = sreg; return i; }
98 2548f?avr?03/2013 atmega406 the following code examples show how to do an at omic write of the tcnt1 register contents. writing to the ocr1a register can be done using the same principle. note: 1. see ?about code examples? on page 7 . the assembly code example requires that the r17: r16 register pair contains the value to be writ- ten to tcnt1. 16.2.1 reusing the temporary high byte register if writing to more than one 16-bit register where the high byte is the same for all registers written, then the high byte only needs to be written once. however, note that the same rule of atomic operation described previously also applies in this case. 16.3 timer/counter clock sources the timer/counter is clocked by an internal clock source. the clock source is selected by the clock select logic whic h is controlled by the clock select (cs1[2:0]) bits located in the timer/counter control register b (tccr1b). for details on clock sources and prescaler, see ?timer/counter0 and timer/counter1 prescalers? on page 103 . assembly code example (1) tim16_writetcnt 1 : ; save global interrupt flag in r18,sreg ; disable interrupts cli ; set tcnt 1 to r17:r16 out tcnt 1 h,r17 out tcnt 1 l,r16 ; restore global interrupt flag out sreg,r18 ret c code example (1) void tim16_writetcnt 1 ( unsigned int i ) { unsigned char sreg; unsigned int i; /* save global interrupt flag */ sreg = sreg; /* disable interrupts */ _cli(); /* set tcnt 1 to i */ tcnt 1 = i; /* restore global interrupt flag */ sreg = sreg; }
99 2548f?avr?03/2013 atmega406 16.4 counter unit the main part of the 16-bit timer/counter is th e programmable 16-bit bi-directional counter unit. figure 16-2 shows a block diagram of the counter and its surroundings. figure 16-2. counter unit block diagram signal description (internal signals): count increment tcnt1 by 1. clear clear tcnt1 (set all bits to zero). clk t 1 timer/counter clock. the 16-bit counter is mapped into two 8-bit i/o memory locations: counter high (tcnt1h) con- taining the upper eight bits of the counter, and counter low (tcnt1l) containing the lower eight bits. the tcnt1h register can only be indirect ly accessed by the cpu. when the cpu does an access to the tcnt1h i/o location, the cpu accesses the high byte temporary register (temp). the temporary register is updated with the tcnt1h value when the tcnt1l is read, and tcnt1h is updated with the temporary register va lue when tcnt1l is written. this allows the cpu to read or write the entire 16-bit counter value within one clock cycle via the 8-bit data bus. it is important to notice that there are special cases of writing to the tcnt1 register when the counter is counting that will gi ve unpredictable results. the s pecial cases are described in the sections where they are of importance. depending on the mode of operation used, the counter is cleared or incremented at each timer clock (clk t 1 ). the clk t 1 is generated from an internal clock source, selected by the clock select bits (cs1[2:0]). when no clock source is select ed (cs1[2:0] = 0) the ti mer is stopped. however, the tcnt1 value can be accessed by t he cpu, independent of whether clk t 1 is present or not. a cpu write overrides (has priority over) all counter clear or count operations. 16.5 output compare unit the 16-bit comparator continuously compares tcnt1 with the output compare register (ocr1a). if tcnt equals ocr1a the comparat or signals a match. a match will set the output compare flag (ocf1a) at the next timer clock cycle. if enabled (ocie1a = 1), the output com- pare flag generates an output compare interrup t. the ocf1a flag is automatically cleared when the interrupt is executed. alternatively the ocf1a flag can be cleared by software by writing a logical one to its i/o bit location. temp (8-bit) data bus (8-bit) tcntn (16-bit counter) tcntnh (8-bit) tcntnl (8-bit) control logic count clear tovn (int.req .) clk tn
100 2548f?avr?03/2013 atmega406 figure 16-3 shows a block diagram of the output comp are unit. the small ?n? in the register and bit names indicates the device number (n = 1 for timer/counter1), and the ?x? indicates output compare unit (a). the elements of the block diagr am that are not directly a part of the output compare unit are gray shaded. figure 16-3. output compare unit, block diagram 16.5.1 compare match blocking by tcnt1 write all cpu writes to the tcnt1 register will block any compare match that occurs in the next timer clock cycle, even when the timer is stopped. this feature allows ocr1x to be initialized to the same value as tcnt1 without triggering an inte rrupt when the timer/counter clock is enabled. 16.5.2 using the output compare unit since writing tcnt1 in any mode of operation will block all comp are matches for one timer clock cycle, there are risks involved when changing tcnt1 when using any of the output compare channels, independent of whether the timer/counter is running or not. if the value written to tcnt1 equals the ocr1x value, t he compare match will be missed. 16.6 16-bit timer/counte r register description 16.6.1 tccr1b ? timer/coun ter1 control register b ? bit 7:4 ? res: reserved bits these bits is a reserved bit in the atmega406 and always reads as zero. ? bit 3 ? ctc1: clear timer/ counter1 on compare match when the ctc1 control bit is set (one), timer/counter1 is reset to 0x00 in the cpu clock cycle after a compare match. ocfnx (int.req.) = (16-bit comparator ) temp (8-bit) data bus (8-bit) tcntn (16-bit counter) tcntnh (8-bit) tcntnl (8-bit) ocrnx (16-bit register) ocrnxh (8-bit) ocrnxl (8-bit) bit 7654 3210 (0x81) ? ? ? ? ctc1 cs12 cs11 cs10 tccr1b read/write r/w r/w r r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
101 2548f?avr?03/2013 atmega406 ? bit 2:0 ? cs1[2:0]: clock select the three clock select bits select the cloc k source to be used by the timer/counter. 16.6.2 tcnt1h and tcnt1l ? timer/counter1 the two timer/counter i/o locations (tcnt1h and tcnt1l, combined tcnt1) give direct access, both for read and for write operations, to the timer/counter unit 16-bit counter. to ensure that both the high and low bytes are read and written simultaneously when the cpu accesses these registers, the access is perfo rmed using an 8-bit temporary high byte register (temp). this temporary register is shared by all the other 16-bit registers. see ?accessing 16-bit registers? on page 96. modifying the counter (tcnt1) while the counte r is running introduces a risk of missing a com- pare match between tcnt1 and one of the ocr1x registers. writing to the tcnt1 register blocks (removes ) the compare match on the following timer clock for all compare units. 16.6.3 ocr1ah and ocr1al ? ou tput compare register 1 a the output compare register contains a 16-bit value that is continuously compared with the counter value (tcnt1). the output compare register is 16-bit in size. to ensure that both the high and low bytes are written simultaneously when the cp u writes to these registers, the access is performed using an 8-bit temporary high byte register (temp). this te mporary register is shared by all the other 16- bit registers. see ?accessing 16-bit registers? on page 96. table 16-1. cs1[2:0] - clock select bit description cs12 cs11 cs10 description 0 0 0 no clock source (timer/counter stopped). 001clk i/o /1 (no prescaling) 010clk i/o /8 (from prescaler) 011clk i/o /32 (from prescaler) 100clk i/o /64 (from prescaler) 101clk i/o /128 (from prescaler) 110clk i/o /256 (from prescaler) 111clk i/o /1024 (from prescaler) bit 76543210 (0x85) tcnt1[15:8] tcnt1h (0x84) tcnt1[7:0] tcnt1l read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0x89) ocr1a[15:8] ocr1ah (0x88) ocr1a[7:0] ocr1al read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
102 2548f?avr?03/2013 atmega406 16.6.4 timsk1 ? timer/counter interrupt mask register 1 ? bit 7:2 ? res: reserved bits these bits are reserved bits in the atmega406 and always reads as zero. ? bit 1 ? ocie1a: timer/counter1, output compare a match interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts globally enabled), the timer/counter1 output compare a match interrupt is enabled. the corresponding interrupt vector (see ?reset and interrupt h andling? on page 14) is executed when the ocf1a flag, located in tifr1, is set. ? bit 0 ? toie1: timer/counter1, overflow interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts globally enabled), the timer/counter1 over flow interrupt is enabled. the corresponding interrupt vector (see ?reset and interrupt handling? on page 14) is executed when the tov1 flag, located in tifr1, is set. 16.6.5 tifr1 ? timer/counter interrupt flag register ? bit 7:2 ? res: reserved bits these bits are reserved bits in the atmega406 and always reads as zero. ? bit 1 ? ocf1a: timer/counter1, output compare a match flag this flag is set in the timer clock cycle afte r the counter (tcnt1) va lue matches the output compare register a (ocr1a). ocf1a is automatically cleared w hen the output compare match a interrupt vector is executed. alternatively, ocf1a can be cleared by writing a logic one to its bit location. ? bit 0 ? tov1: timer/counter1, overflow flag tov1 flag is set when the timer overflows. tov1 is automatically cleared when the timer/c ounter1 overflow interrupt vector is executed. alternatively, tov1 can be cleared by writing a logic one to its bit location. bit 7 6 5 4 3 2 1 0 (0x6f) ????? ?ocie1atoie1timsk1 read/write rrrrr rr/wr/w initial value 0 0 0 0 0 0 0 0 bit 76543210 0x16 (0x36) ??????ocf1atov1tifr1 read/write rrrrrrr/wr/w initial value 0 0 0 0 0 0 0 0
103 2548f?avr?03/2013 atmega406 17. timer/counter0 and ti mer/counter1 prescalers timer/counter1 and time r/counter0 share the same prescale r module, but the timer/counters can have different prescaler settings. the description below applies to both timer/counter1 and timer/counter0. 17.1 internal clock source the timer/counter can be clocked directly by the system clock (by setting the csn2:0 = 1). this provides the fastest operation, with a maximum timer/counter clock frequency equal to system clock frequency (f clk_i/o ). alternatively, one of the taps from the prescaler can be used as a clock source by setting the csn2:0. see table 15-9 on page 92 for timer/counter0 settings and table 16-1 on page 101 for timer/counter1 settings. the prescaled clock has a frequency of either f clk_i/o /8, f clk_i/o /32, f clk_i/o /64, f clk_i/o /128, f clk_i/o /256, or f clk_i/o /1024. 17.2 prescaler reset the prescaler is free running, i.e., operates independently of the clock select logic of the timer/counter, and it is shared by timer/counter1 and timer/counter0. since the prescaler is not affected by the timer/counter? s clock select, the state of t he prescaler will have implications for situations where a prescaled clock is used. one example of prescaling artifacts occurs when the timer is enabled and clocked by the prescaler (6 > csn2:0 > 1). the number of system clock cycles from when the timer is enabled to the first count occurs can be from 1 to n+1 system clock cycles, where n equals the prescaler divisor. it is possible to use the prescaler reset for synchronizing the timer/counter to program execu- tion. however, care must be taken if the othe r timer/counter that shares the same prescaler also uses prescaling. a prescaler reset will affect the prescaler period for all timer/counters it is connected to. 17.3 external clock source an external clock source applied to the t0 pin can be used as timer/counter0 clock (clkt0). the t0 pin is sampled once every system clock cycle by the pin synchronization logic. the synchro- nized (sampled) signal is then passed through the edge detector. figure 17-1 shows a functional equivalent block diagram of the t0 synchronization and edge detector logic. the registers are clocked at the positive edge of the internal system clock ( clk i/o ). the latch is transparent in the high period of the internal system clock. the edge detector generates one clk t 0 pulse for each positive (csn2:0 = 7) or negative (csn2:0 = 6) edge it detects. figure 17-1. t1/t0 pin sampling tn_sync (to clock select logic) edge detector synchronization dq dq le dq tn clk i/o
104 2548f?avr?03/2013 atmega406 the synchronization and e dge detector logic introduces a de lay of 2.5 to 3.5 system clock cycles from an edge has been applied to the t0 pin to the counter is updated. enabling and disabling of the clock input must be done when t0 has been stable for at least one system clock cycle, otherwise it is a risk that a false timer/counter clock pulse is generated. each half period of the exter nal clock applied must be longer than one system clock cycle to ensure correct sampling. the external clock must be guaranteed to have less than half the sys- tem clock frequency (f extclk < f clk_i/o /2) given a 50/50% duty cycle. since the edge detector uses sampling, the maximum frequency of an external clock it can detect is half the sampling fre- quency (nyquist sampling theorem). however, due to variation of the system clock frequency and duty cycle caused by oscillator source (crystal, resonator, and capacitors) tolerances, it is recommended that maximum frequency of an external clock source is less than f clk_i/o /2.5. an external clock source can not be prescaled. figure 17-2. prescaler for timer/counter0 and timer/counter1 (1) note: 1. the synchronization logic on the input pins ( t1/t0) is shown in figure 17-1 . psrsync clear clk t1 clk t0 t0 clk i/o synchronization ck/32 ck/8 ck/64 ck/256 ck/128 ck/1024
105 2548f?avr?03/2013 atmega406 17.4 register description 17.4.1 gtccr ? general timer/counter control register ? bit 7 ? tsm: timer/counter synchronization mode writing the tsm bit to one activa tes the timer/counter synchroniz ation mode. in this mode, the value that is written to the psrsync bit is kept, hence keeping the corresponding prescaler reset signals asserted. this ensures that the corresponding timer/counters are halted and can be configured to the same value without the risk of one of them advancing during configuration. when the tsm bit is written to zero, the psrsync bit is cleared by hardware, and the timer/counters start counting simultaneously. ? bit 0 ? psrsync: prescaler reset when this bit is one, timer/co unter1 and timer/counter 0 prescaler will be reset. this bit is nor- mally cleared immediately by hardware, except if the tsm bit is set. note that timer/counter1 and timer/counter0 share the same prescaler and a reset of this presca ler will affect both timers. bit 7654321 0 0x23 (0x43) tsm ? ? ? ? ? ? psrsync gtccr read/writer/wrrrrrrr/w initial value 0 0 0 0 0 0 0 0
106 2548f?avr?03/2013 atmega406 18. coulomb counter - dedicated fuel gauging sigma-delta adc 18.1 features ? sampled system coulomb counter ? low power sigma-delta adc opti mized for coulomb counting ? instantaneous current output with 3.9 ms conversion time ? accumulate current output with programmable conversion time: 125/250/500/1000 ms ? input voltage range larger than 0.15v, allowing measurement of more than 30a @ 5 m ? ? 13-bit resolution (including sign) corresponding to 53.7 v (10.7 ma @ 5 m ? ) for instantaneous current output ? 18-bit resolution (including sign) corresponding to 1.68 v (0.335 a @ 5 m ? ) for accumulate current output ? input offset less th an 10 v for the adc ? interrupt on instantaneous current conversion complete ? interrupt on accumulate current conversion complete ? interrupt on regular current with programmable compare level and programmable sampling interval: 250/500/1000/2000 ms atmega406 features a dedicated sigma-delta ad c (cc-adc) optimized for coulomb counting to sample the charge or discharge current fl owing through the exter nal sense resistor r sense . two different output values are provided, instantaneous current and accumulate current. the instantaneous current output has a short conversi on time at the cost of lower resolution. the accumulate current output provides a highly accurate current measurement for coulomb counting. the sampling coulomb counter provides a highly accurate and flexible solution. accuracy can easily be traded against conversion time. it also provides regular current detection. this allows ultra-low power operation in power-save mode when small charge or discharge currents are flowing. figure 18-1. coulomb counter block diagram sigma delta modulator current comparator control & status register irq 8-bit databus r sense pi ni regular current irq level decimation instantaneous current decimation irq irq accumulate current
107 2548f?avr?03/2013 atmega406 18.2 operation when enabled, the cc-adc continuously measures the voltage over the ex ternal sense resistor r sense . the instantaneous current conversion time is fix ed to 3.9 ms (typical value) allowing the output value to closely follow the input. after each instantaneous current conversion an interrupt is generate if the interrupt is enab led. data from conversion will be updated in the instantaneous current registers - cadicl and cadich simultaneousl y as the interrupt is given. to avoid los- ing conversion data, both the low and high byte must be read within a 3,9 ms timing window after the corresponding interrupt is give n. when the low byte register is read, updating of the instanta- neous current registers and interrupts will be stopped unt il the high byte is read. figure 18-2 shows an instantaneous current conversion diagram, where data4 will be lost because data3 reading is not completed within the limited period. figure 18-2. instantaneous current conversion the accumulate current output is a high-resolution, high accuracy output with programmable conversion time selected by the cadas bits in cadcsra. the converted value is an accurate measurement of the average current flow during one conversion period. the cc-adc generates an interrupt each time a new accumulate current conversion has finished if the interrupt is enabled. data from conv ersion will be updated in the accumulation current registers - cadac0, cadac1, cadac2 and cadac3 simultaneously as the interrupt is given. to avoid losing con- version data, all bytes must be read within the selected conver sion period. when the lower byte registers are read, updating of the accumulation current regi sters and interr upts will be stopped until the highest byte is read. figure 18-3 on page 108 shows an accumulation current conver- sion example, where data4 will be lost because data3 reading is not completed within the limited period. enable instantaneous interrupt instantaneous data read low byte read high byte data1 data 2 data 3 data 5 setting of digital filters ~12 ms settling 3.9 ms 3.9 ms 7.8 ms
108 2548f?avr?03/2013 atmega406 figure 18-3. accumulation current conversion while the cc-adc is converting, the cpu can enter sleep mode and wait for an interrupt from the accumulate current conversi on. after adding the new accu mulate current value for cou- lomb counting, the cpu can go back to sleep again. this reduces the cpu workload, and allows more time spent in lo w power modes, reducing power consumption. the cc-adc can generate an interrupt if the result of an instan taneous current conversi on is greater than a pro- grammable threshold. this allo ws the detection of a regular current conditi on. this function is available in active mode and all sleep modes except power-down and power-off mode. this allows an ultra-low power operation in power-save, where the cc-adc can be configured to enter a regular current detection mode with a programmable current sampling interval. by set- ting the cadse bit in cadcsra, the coulomb counter will repeatedly do one instantaneous current conversion, before it is being turned off for a timing interval specified by the cadsi bits in cadcsra. this allows operating the regula r current detection while keeping the coulomb counter off most of the time. the coulomb counter is halted in power-down mo de. in this mode, time measurements and the battery self-discharge characteri stics should be used to estimate the charge flow. when waking up from power-down mode, the cc-adc will au tomatically resume co ntinuous operation. the cc-adc is enabled by setting the cc-adc enable bit, caden, in cadcsra. note that the bandgap voltage reference must be enabled separately, see ?bgccr ? bandgap calibration c register? on page 123 . the cc-adc will not consume power when cade n is cleared. it is therefore recommended to switch off the cc-adc whenever the coulomb counter or regular current detection functions are not used. the cc-adc is automatically disabled in power-down and power-off mode. after the cc-adc is enabled, eit her by setting the caden bi t or leaving power-down with caden already set, the first four conversions do not contain useful data and should be ignored. this also applies after clearing the cadse bit. in-system offset voltage for the cc-adc is typica lly in the range 0 - 100 v. to compensate for this offset error, a cc-adc offs et value should be stored in eeprom and subtracted from each accumulate current conversions before the result ing value is added for coloumb counting. the cc-adc offset value can be found by performing a cc-adc conversion at typical temperature with zero current flowing through r sense . when the battery is not used or the current level stays very low for a long time, it is recom- mended to estimate the charge flow instead of using the cc-adc for coloumb counting. the enable accumulation interrupt accumulation data read byte 1 read byte 2 read byte 3 read byte 4 data1 data 2 data 3 data 5 setting of digital filters 125, 250, 500, or 1000 ms 250, 500, 1000, or 2000 ms 125, 250, 500, or 1000 ms
109 2548f?avr?03/2013 atmega406 charge flow estimation should be based on the se lf-discharge rate of the battery and the standby current of the battery system. 18.2.1 cadcsra ? cc-adc contro l and status register a ? bit 7 ? caden: cc-adc enable when the caden bit is cleared (zero), the cc-adc is disabled, and any ongoing conversions will be terminated. when the caden bit is set (o ne), the cc-adc will continuously measure the voltage drop over the external sense resistor r sense . in power-off, the cc-adc is always dis- abled. note that the bandgap voltage refe rence must be enabled separately, see ?bgccr ? bandgap calibration c register? on page 123 . ? bit 6 ? res: reserved this bit is reserved bit in the at mega406 and will always read as zero. ? bit 5 - cadub: cc-adc update busy the cc-adc operates in a different clock domain than the cpu. whenever a new value is writ- ten to cadcsra, cadrcc or cadrdc, this value must be synchronized to the cc-adc clock domain. subsequent writes to these registers will be blo cked during this synchronization. syn- chronization of one of the registers, will blo ck updating of all the others . the cadub bit will be read as one while any of these registers is being synchronized , and will be read as zero when neither register is being synchronized. ? bits 4:3 ? cadas1:0: cc-adc accumulate current select the cadas bits select the conversion time for the accumulate current output as shown in table 18-1 . bit 765 4 3 210 (0xe4) caden ? cadub cadas1 cadas0 cadsi1 cadsi0 cadse cadcsra read/write r/w r r r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 18-1. cc-adc accumulate current conversion time cadas1:0 cc-adc accumulate current conversion time 00 125 ms 01 250 ms 10 500 ms 11 1 s
110 2548f?avr?03/2013 atmega406 ? bits 2:1 ? cadsi1:0: cc-adc current sampling interval the cadsi bits determine the current sampling interval for the regular current detection as shown in table 18-2 . the current sampling interval is on ly used if the cadse bit is set. notes: 1. the actual value of depends on the actual frequency of the ?slow rc oscillator? on page 27 . see ?electrical characteristics? on page 225 . 2. sampling time ~ 12 ms. ? bit 0 ? cadse: cc-adc current sampling enable when the cadse bit is written to one, the ongoi ng cc-adc conversion is aborted, and the cc- adc enters regular current detection mode. 18.2.2 cadcsrb ? cc-adc contro l and status register b ? bits 7, 3 ? res: reserved these bits are reserved bits in the atmega406 and will always read as zero. ? bit 6 ? cadacie: cc-adc accumu late current interrupt enable when the cadacie bit is set (one), and the i-bit in the status register is set (one), the cc-adc accumulate current interrupt is enabled. ? bit 5 ? cadrcie: cc-adc regu lar current interrupt enable when the cadrcie bit is set (one), and the i-bit in the status register is set (one), the cc-adc regular current interrupt is enabled. ? bit 4 ? cadicie: cc-adc instan taneous current interrupt enable when the cadicie bit is set (one), and the i-bit in the status register is set (one), the cc-adc instantaneous current interrupt is enabled. ? bit 2 ? cadacif: cc-adc accumu late current interrupt flag the cadacif bit is set (one) after the accumula te current conversion has completed. the cc- adc accumulate current interrupt is executed if the cadacie bit and the i-bit in sreg are set (one). cadacif is cleared by hardware when executing the correspondi ng interrupt handling vector. alternatively, cadacif is clea red by writing a logic one to the flag. ? bit 1 ? cadrcif: cc-adc regular current interrupt flag table 18-2. cc-adc regular current sampling interval cadsi1:0 cc-adc regular current sampling interval (1)(2) 00 250 ms (+ sampling time) 01 500 ms (+ sampling time) 10 1 s (+ sampling time) 11 2 s (+ sampling time) bit 7 6 5 4 3 2 1 0 (0xe5) ? cadacie cadrcie cadicie ? cadacif cadrcif cadicif cadcsrb read/write r r/w r/w r/w r r/w r/w r/w initial value 0 0 0 0 0 0 0 0
111 2548f?avr?03/2013 atmega406 the cadrcif bit is set (one) when the absolute va lue of the result of the last cc-adc conver- sion is greater than, or equal to, the compare values set by the cc-adc regular charge/discharge current level registers. a posi tive value is compared to the regular charge current level, and a negative value is compared to the regular discharge current level. the cc-adc regular current interrupt is executed if the cadrcie bit and the i-bit in sreg are set (one). cadrcif is cleared by hardware when ex ecuting the corresponding interrupt handling vector. alternatively, cadrcif is cleared by writing a logic one to the flag. ? bit 0 ? cadicif: cc-adc instan taneous current interrupt flag the cadicif bit is set (one) when a cc-adc instantaneous current conversion is completed. the cc-adc instantaneous current interrupt is executed if the cadicie bit and the i-bit in sreg are set (one). cadicif is cleared by hardware when executing the corresponding inter- rupt handling vector. alternativ ely, cadicif is cleared by wr iting a logic one to the flag. 18.2.3 cadich and cadicl ? cc-adc instantaneous current when a cc-adc instantaneous current conversion is complete, the result is found in these two registers. cadic15:0 represents the converted result in 2's complement format, sign extended to 16 bits. when cadicl is read, the cc-a dc instantaneous current register is not updated until cadch is read. reading the registers in the sequence cadicl, cadich will ensure that consistent val- ues are read. 18.2.4 cadac3, cadac2, cadac1 and cadac0 ? cc-adc accumulate current the cadac3, cadac2, cadac1 and cadac0 registers contain the accumulate current measurements in 2?s complement format, sign extended to 32 bits. bit 151413121110 9 8 (0xe9) cadic[15:8] cadich (0xe8) cadic[7:0] cadicl bit 76543210 read/write rrrrrrrr rrrrrrrr initial value00000000 00000000 bit 3130292827262524 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 76543210 (0xe3) cadac[31:24] cadac3 (0xe2) cadac[23:16] cadac2 (0xe1) cadac[15:8] cadac1 (0xe0) cadac[7:0] cadac0 read/write rrrrrrrr rrrrrrrr rrrrrrrr initial value 00000000 00000000 00000000
112 2548f?avr?03/2013 atmega406 when cadac0 is read, the cc-a dc accumulate current register is not updated until cadac3 is read. reading the registers in the se quence cadac0, cadac1, cadac2, cadac3 will ensure that consistent values are read. 18.2.5 cadrcc ? cc-adc regular charge current the cc-adc regular charge current register determines the threshold level for the regular charge current detection. when the result of a cc-adc instantaneous current conversion is positive with a value greater than, or equal to, the regular charge current level, the cc-adc regular current interrupt flag is set. the value in this register is s pecified in 2's complement format, and it defines the eight least sig- nificant bits of the regular char ge current level. the most signif icant bits of the regular charge current level are always zero. the programmable range for the regular ch arge current level is given in table 18-3 . the cc-adc regular charge current register does not affect the setting of the cc-adc con- version complete interrupt flag. 18.2.6 cadrdc ? cc-adc regular discharge current the cc-adc regular discharge current register determines the threshold level for the regular discharge current detection. when the result of a cc-adc instantaneous current conversion is negative with an absolute value greater than, or equal to, the regular discharge current level, the cc-adc regular current interrupt flag is set. the value in this register is s pecified in 2's complement format, and it defines the eight least sig- nificant bits of the re gular discharge current level. the mo st significant bits of the regular bit 76543210 (0xe6) cadrcc[7:0] cadrcc read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 00000000 table 18-3. programmable range for the regular charge current level minimum maximum step size voltage (v) 0 13700 53.7 current (ma) r sense = 5 m ? 0 2740 10.7 r sense = 7 m ? 0 1957 7.7 bit 7 6 5 43210 (0xe7) cadrdc[7:0] cadrdc read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value0 0 0 00000
113 2548f?avr?03/2013 atmega406 charge current level are always one. the pr ogrammable range for the regular discharge cur- rent level is given in table 18-4 . the cc-adc regular discharge current register does not affect the setting of the cc-adc conversion complete interrupt flag. table 18-4. programmable range for the regular discharge current level minimum maximum step size voltage (v) 0 13700 53.7 current (ma) r sense = 5 m ? 0 2740 10.7 r sense = 7 m ? 0 1957 7.7
114 2548f?avr?03/2013 atmega406 19. voltage regulator 19.1 features ? linear regulation. ? operating voltage range 4.0 - 25v. ? fixed output voltage at 3.3v. atmega406 is supplied by the vfet terminal. o perating voltage range at the vfet terminal is 4.0 - 25v. the internal voltage regulator regulate s this voltage down to 3.3v, which is a suitable supply voltage for the internal logi c, i/o lines, and analog circuitry. an external decoupling capacitor of 1 f or larger is required for stable operation of the voltage regulator. a larger capacito r will allow larger load curren ts and increase start-up time. the block diagram of the voltage regulator is shown in figure 19-1 . figure 19-1. voltage regulator block diagram 19.2 operation the regulator will operate in all sleep modes, including powe r-off. in this mode the regulator will automatically reduce the atmega406's power consumption by turning off supply for all periph- eral modules, allowing only the charger dete ct module and the voltage regulator itself to operate. the regulator will automatica lly ensure that it has stable work conditions before allowing itself to start regulating the vfet terminal . if the voltage at the vfet pin is below the regulator-on threshold voltage, v rot , the ldo will be switched off. powering-up the regulator is either done from the battery side when the smart battery controller is assembled with the battery pack and there is no charger present, or from the charger side when a deep discharge has occurred (0v charging). when powering- up with a charger present, the voltage between the vfet and the pvt pin must be above a charge-threshold voltage, v cht . ldo regulator regulator control creg > 1 u f vfet power distributor pvt ldo_on pv1 rsense rp rn vreg voltage regulator analog supply digital supply power_off
115 2548f?avr?03/2013 atmega406 when powering-up without a charger present, t he voltage on cell1, vpv1, must be above the cell1-threshold voltage, vpv1t. after powering-up the regulato r the chip will enter power-off sleep mode (lowest power con- sumption). until a charger is detected, the chip will stay in this mode. for details on charger detect, see ?power-on reset and charger connect? on page 40 . table 30-2 on page 230 shows the characteristics for powering-up the ldo.
116 2548f?avr?03/2013 atmega406 20. voltage adc ? 10-channel gene ral purpose 12-bit sigma-delta adc 20.1 features ? 12-bit resolution ? 1 lsb accuracy ? 519s conversion time ? four differential input channels for cell voltage measurements ? six single ended input channels ? 0 to 0.9 x vref input voltage range ? 0.2x pre-scaling of cell voltages and vreg ? interrupt on v-adc conversion complete the atmega406 features a 12-bit sigma-delta adc. automatic offset cancellation technique reduces the input offset voltage to less than 0.5 mv. the voltage adc (v-adc) is connected to ten di fferent sources through the input multiplexer. there are four differential channels for cell voltage measurements. these channels are scaled 0.2x to comply with the full scale range of th e v-adc. in addition there are six single ended channels referenced to sgnd. one channel is for measuring the internal temperature sensor vptat and five channels for measuring the adc input pins at port a. adc3:0 are not scaled, meaning that full-scale reading co rresponds to 1.1 v. adc4 is sca led by 0.2x, meaning that full- scale reading corresponds to 5.5 v. the adc4 input can be used to measure the voltage at the pa4 pin when this pin is used to supply an external thermistor, see figure 29-1 on page 223 . to obtain a total absolute accuracy better than 0.25% for the cell voltage measurements, cali- bration registers for the individual cell voltage gain in the analog front-end is provided. a factory calibration value is stored in the signature row, see section 27.7.10 ?reading the signature row from software? on page 189 . the v-adc conversion of a cell voltage must be scaled with the corresponding calibration value by software to correct for gain error in the analog front-end. the prvadc bit in ?prr0 ? power reduction register 0? on page 36 must be written to zero to enable v-adc module.
117 2548f?avr?03/2013 atmega406 figure 20-1. voltage adc block schematic 20.2 operation to enable v-adc conversions, the v-adc enable bit, vaden, in v-adc control and status register ? vadcsr must be set. if this bit is cleared, the v-adc will be switched off, and any ongoing conversions will be te rminated. the v-adc is automa tically halted in power-save, power-down and power-off mode. note that the bandgap voltage reference must be enabled and disabled separately, see ?bgccr ? bandgap calibration c register? on page 123. figure 20-2. voltage adc conversion diagram to perform a v-adc conversion, the analog input c hannel must first be selected by writing to the vadmux bits in vadmux. when a logical one is written to t he v-adc start conversion bit vadsc, a conversion of the selected channel will star t. the vadsc bit stays high as long as the conversion is in progre ss and will be cleared by hardware when the conversion is completed. if a different data channel is selected while a conversi on is in progress, the adc will finish the cur- rent conversion before performi ng the channel change. when a c onversion is finished the v- v-adc conversion complete irq 8-bit data bus v-adc multiplexer sel. reg (vadmux) v-adc control and status reg (vadcsr) v-adc data register (vadcl/adch) vadccie vadccif 12-bit sigma-delta adc input mux v-adc control adc3 adc2 adc1 adc0 v temp adc4 pv4 pv3 pv2 pv1 nv note: the shaded signals are scaled by 0.2, other signals are scaled by 1.0 vref sgnd start conversion interrupt conversion result invalid data invalid data old data valid data 519 us
118 2548f?avr?03/2013 atmega406 adc conversion complete interrupt flag ? vadcc if is set. one 12-bit conversion takes 519 s to complete from the start bit is set to the interrupt flag is set. to ensure that correct data is read, both high and low byte data registers should be read before starting a new conversion. 20.3 register description 20.3.1 vadmux ? v-adc mult iplexer selection register ? bit 7:4 ? res: reserved bits these bits are reserved bits in the atmega406 and will always read as zero. ? bit 3:0 ? vadmux3:0: v-adc channel selection bits the vadmux bits determine the v-adc channel selection. see table 20-1 on page 118 . 20.3.2 vadcsr ? v-adc control and status register ? bit 7:4 ? res: reserved bits these bits are reserved bits in the atmega406 and will always read as zero. ? bit 3 ? vaden: v-adc enable writing this bit to one enables v-adc conversion. by wr iting it to zero, th e v-adc is turned off. turning the v-adc off while a conversion is in progress will te rminate this conv ersion. note that the bandgap voltage reference must be enabled separately, see ?bgccr ? bandgap calibra- tion c register? on page 123. bit 7654 3 2 1 0 (0x7c) ? ? ? ? vadmux3 vadmux2 vadmux1 vadmux0 vadmux read/write r r r r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 20-1. vadmux channel selection vadmux3:0 channel selected scale 0001 cell 1 0.2 0010 cell 2 0.2 0011 cell 3 0.2 0100 cell 4 0.2 0101 adc4 0.2 0110 vtemp 1.0 0111 adc0 1.0 1000 adc1 1.0 1001 adc2 1.0 1010 adc3 1.0 bit 76543210 (0x7a) ?? ? ? vaden vadsc vadccif vadccie vadcsr read/write r r r r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
119 2548f?avr?03/2013 atmega406 ? bit 2 ? vadsc: voltage adc start conversion write this bit to one to start a new conversion of the selected channel. vadsc will read as one as long as the conversion is not finished. when the conversion is com- plete, it returns to zero. writing zero to this bit has no effect. vadsc will automatically be cleared when the vaden bit is written to zero. ? bit 1 ? vadccif: v-adc con version complete interrupt flag this bit is set when a v-adc conversion comple tes and the data registers are updated. the v- adc conversion complete interrupt is executed if the vadccie bit and the i-bit in sreg are set. vadccif is cleared by hardware when exec uting the corresponding interrupt handling vec- tor. alternatively, vadccif is cl eared by writing a logical one to the flag. beware that if doing a read-modify-write on vadcsr, a p ending interrupt can be disabled. ? bit 0 ? vadccie: v-adc conver sion complete interrupt enable when this bit is written to one and the i-bit in sreg is set, the v-ad c conversion complete interrupt is activated. 20.3.3 vadcl and vadch ? the v-adc data register when a v-adc conversion is complete, the result is found in these two registers. to ensure that correct data is read, the data registers must be read before starting a new conversion. ? vadc11:0: v-adc conversion result these bits represent the result from the conversion. to obtain the best absolute accuracy for the cell voltage measurements, gain and offset com- pensation is required. factory calibration values are stored in the device signature row, refer to section ?reading the signature row from software? on page 189 for details. the cell voltage in mv is given by: when performing a vtemp conversion, the result must be adjusted by the factory calibration value stored in the signature row, refer to section ?reading the signature row from software? on page 189 for details. the absolute temperature in kelvin is given by: bit 15 14 13 12 11 10 9 8 (0x79) ? ? ? ? vadc[11:8] vadch (0x78) vadc[7:0] vadcl 7 6 54 3 2 10 read/writer r rr r r rr r r rr r r rr initial value 0 0 0 0 0 0 0 0 0 0 00 0 0 00 cell n voltage mv ?? cell n result cell n gain calibration word ? tbd --------------------------------------------------------------------------------------------------- cell n offset calibration word ? = t(k) v temp result vptat calibration word ? tbd ------------------------------------------------------------------------------------------------ =
120 2548f?avr?03/2013 atmega406 20.3.4 didr0 ? digital i nput disable register 0 ? bits 7:4 ? res: reserved bits these bits are reserved for future use. to ensure compatibility with future devices, these bits must be written to zero when didr0 is written. ? bit 3:0 ? vadc3d:vadc0d: v- adc3:0 digital input disable when this bit is written logic one, the digital in put buffer on the corresponding v-adc pin is dis- abled. the corresponding pin regist er bit will always read as zero when this bit is set. when an analog signal is applied to the vadc3:0 pin and t he digital input from this pin is not needed, this bit should be written logic one to reduce power consumption in the digital input buffer. bit 7 6 5 4 3 2 1 0 (0x7e) ? ? ? ? vadc3d vadc2d vadc1d vadc0d didr0 read/write r r r r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
121 2548f?avr?03/2013 atmega406 21. voltage reference and temperature sensor 21.1 features ? accurate voltage reference of 1.100v ? 0.1% accuracy after calibration (2 mv calibration steps) ? temperature drift less than 80 ppm/c after calibration ? alternate low power voltage reference for voltage regulator ? internal temperature sensor ? possibility for runtime compensation of temper ature drift in both voltage reference and on- chip oscillators ? external decoupling for optimum noise performance ? low power consumption a low power band-gap reference provides atmega406 with an accurate on-chip voltage refer- ence v ref of 1.100v. this reference voltage is used as reference for the on-chip voltage regulator, the v-adc and the cc-adc. the referenc e to the adcs uses a buffer with external decoupling capacitor to enable excellent nois e performance with mini mum power consumption. the reference voltage v ref_p /v ref_n to the cc-adc is scaled to match the full scale require- ment at the current sense input pins. this configuration also enables concurrent operation of both v-adc and cc-adc. to guaranty ultra low temperature drift after fa ctory calibration, atmega 406 features a two-step calibration algorithm. the first step is performed at 85 ? c and the second at room temperature. by default, atmel factory ca libration is performed at 85 ? c, and the result is stored in flash. the customer can easily implement the second calibrati on step in their test flow. this requires an accurate input voltage and a stable room temper ature. temperature drift after this calibration is guarantied by design and characterization to be less than 80 ppm/ ? c from 0 ? c to 60 ? c and 100 ppm/ ? c from 0 ? c to 85 ? c. the bg calibration c register can also be altered runtime to imple- ment temperature compensation in software. very high accuracy for any temperature inside the temperature range can thus be achieved at the cost of extra calibration steps. a lower power, less accurate voltage reference source exists. this voltage reference source is chosen as reference for the voltage regulator whenever the band-gap voltage reference is dis- abled. this voltage reference source is not available for the v-adc and cc-adc. atmega406 has an on-chip temperature sensor for monitoring the die temperature. a voltage proportional-to-absolute-temperature, v ptat , is generated in the voltage reference circuit and connected to the multiplexer at the v-adc inpu t. this temperature sensor can be used for run- time compensation of temperatur e drift in both the vo ltage referenc e and the on-chip oscillator. to get the absolute temperature in degrees kelvin, the measured v ptat voltage must be scaled with the vptat factory calibration value stored in the signature row. see ?reading the signature row from software? on page 189 for details.
122 2548f?avr?03/2013 atmega406 figure 21-1. reference circuitry 21.2 writing to bandgap calibration registers when the calibration registers are changed it wil l affect both the voltage regulator output and bod-level. the bod will react quickly to new detecti on levels, while the re gulator will adjust the voltage more slowly, depending on the size of the external decoupling capacitor. to avoid that a bod-reset is issued when calibration is done, it is recommended to change the values of the bgcc and bgcr bits stepwise, with a step size of 1, and with a ho ld-off time between each step. the hold-off time depends on the size of the vo ltage regulators external decoupling capacitor. for details, see table 21-1 . bg reference vref vref_p vref_n vref_gnd cref v p tat 1.1v 0.22v table 21-1. hold-off times depending on creg. regulator cap hold-off time bgccr hold-off time bgcrr 1 ? f1.2 ? s3.0 ? s 2 ? f2.4 ? s6.0 ? s 3 ? f3.6 ? s9.0 ? s 4 ? f4.8 ? s 12.0 ? s 5 ? f6.0 ? s 15.0 ? s 6 ? f7.2 ? s 18.0 ? s 7 ? f8.4 ? s 21.0 ? s 8 ? f9.6 ? s 24.0 ? s 9 ? f 10.8 ? s 27.0 ? s 10 ? f 12.0 ? s 30.0 ? s
123 2548f?avr?03/2013 atmega406 21.3 register description for voltage reference and temperature sensor 21.3.1 bgccr ? bandgap calibration c register ?bit 7 - bgen this bit is not available from revision e and on of the atmega406. a complete description is found in the revision a of this document. ? bit 6 ? res: reserved bit this bit is reserv ed for future use. ? bit 5:0 ? bgcc5:0: bg calibration of ptat current these bits are used for trimming of the nominal value of the bandgap reference voltage. these bits are binary coded. minimum vref: 000000, maximum vref: 111111. step size approxi- mately 2 mv. 21.3.2 bgcrr ? bandgap calibration r register ? bit 7:0 ? bgcr7:0: bg calibration of resistor ladder these bits are used for temperature gradien t adjustment of the bandgap reference. figure 21-2 illustrates vref as a function of temperature. vref has a positive temperature coefficient at low temperatures and negative temperature coe fficient at high temperatures. depending on the process variations, the top of the vref curve may be located at higher or lower temperatures. to minimize the temperat ure drift in the temperat ure range of interest, bgcrr is used to adjust the top of the curve towards the centre of the te mperature range of interest. the bgcrr bits are temperature coded resulting in 9 possible settings: 00000000, 00000001, 00000011, 00000111, ? , 11111111. the value 00000000 shifts the top of the vref curve to the highest possible temperature, and the value 11111111 shifts the top of the vref curve to the lowest possible temperature. bit 7 6543 210 (0xd0) bgen ? bgcc5 bgcc4 bgcc3 bgcc2 bgcc1 bgcc0 bgccr read/write r r r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 7 6543 210 (0xd1) bgcr7 bgcr6 bgcr5 bgcr4 bg cr3 bgcr2 bgcr1 bgcr0 bgcrr read/write r/w r/w r/ w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
124 2548f?avr?03/2013 atmega406 figure 21-2. illustration of vref as a function of temperature. 0 0.5 1 1.5 -40 -20 0 20 40 60 80 10 0 temperature [ o c] vref [v] temperature range of interest bgcrr is used to move the top of the vref curve to the center of the tempearture range of interest.
125 2548f?avr?03/2013 atmega406 22. battery protection 22.1 features ? deep under-voltage protection ? charge over-current protection ? discharge over-current protection ? short-circuit protection ? programmable and lockable detection levels and reaction times ? autonomous operation independent of cpu if the voltage at the vfet pin falls below the programmable deep under-voltage detection level, c-fet, pc-fet, and d-fet are disabled and the chip is set in power-off mode to reduce power consumption to a minimum. the current battery protection circuitry (cbp) monitors the charge and discharge current and disables c-fet, pc-fet, and d-fet if an ove r-current or short-circuit condition is detected. there are three different programmable detection levels: discharge over-current detection level, charge over-current dete ction level and short-circuit dete ction level. the external filter at the pi/ni input pins will cause too large del ay for short-circuit detection. therefore the sepa- rate ppi/nni inputs are used for current battery protection. there are two different programmable delays for activating current batt ery protection: short-ci rcuit reaction time and over-current reaction time. after current battery protection has been activated, the application software must re-enable the fets. the battery prot ection hardware provides a hold-off time of 1 second before software can re-enab le the discharge fet. this provides safety in case the appli- cation software should unintentionally re-enable the discharge fet too early. the activation of a protection also issues an interrupt to the cpu. the battery protection inter- rupts can be individually enabled and disabled by the cpu. the effect of the various battery protection types is given in table 22-1 . in order to reduce power consumption, both sh ort-circuit and discharge over-current protection are automatically deactivated when the d-fet is disabled. the charge over-current protection is disabled when both the c-fet and the pc-fet are disabled. note however that charge over- current protection is never automatically disabl ed when any of the c-fet or pc-fets are con- trolled by pwm. table 22-1. effect of battery protection types battery protection type interrupt requests c-fet d-fet pc-fet cell balancing fets mcu deep under-voltage detected cpu reset on exit disabled disabled disabled disabled power-off discharge over-current protection entry and exit disabled disabled disabled operational operational charge over-current protection entry and exit disabled disabled disabled operational operational short-circuit protection entry and exit disabled disabled disabled operational operational
126 2548f?avr?03/2013 atmega406 22.2 deep under-voltage protection the deep under-voltage pr otection ensures that th e battery cells will not be discharged deeper than the programmable deep under-v oltage detection level. if the voltage at the vfet pin is below this level for a time longer than the programmable delay time, c-fet, pc-fet and d-fet are automatically switched off and the chip en ters power-off mode. the deep under-voltage early warning interrupt flag (duvif) will be set 250 ms before the chip enters power-off. this will give the cpu a chance to take necessar y actions before the power is switched off. the device will remain in the power-off mode until a charger is connec ted. when a charger is detected, a normal power-up sequence is starte d and the chip initializ es to default state. the deep under-voltage delay time and deep under-voltage detection level are set in the bat- tery protection deep under-voltage register (bpduv). the parameter registers can be locked after the initial configur ation, prohibiting any further upda tes until the next hardware reset. refer to ?register description for battery protection? on page 128 for register descriptions. 22.3 discharge over-current protection the current battery protection (cbp) monitors the cell current by sampling the shunt resistor voltage at the ppi/nni input pins. a differential operational amplifier amp lifies the voltage with a suitable gain. the output from the operational amplifier is compared to an accurate, programma- ble on-chip voltage reference by an analog compar ator. if the shunt resistor voltage is above the discharge over-current detection level for a time longer than over-cu rrent protection reac- tion time, the chip activates discharge over-current protecti on. a sampled system clocked by the internal ulp oscillator is us ed for over-current a nd short-circuit protection. this ensures a reliable clock source, off-set cancellation and low power consumption. when the discharge over-current protection is ac tivated, the external d-fet, pc-fet, and c- fet are disabled and a current protection timer is started. this timer ensures that the fets are disabled for at least one second. the applicati on software must then set the dfe and cfe bits in the fet control and status register to re-enab le normal operation. if the d-fet is re-enabled while the loading of the battery still is too large, the discharge over-current protection will be activated again. 22.4 charge over-cur rent protection if the voltage at the ppi/nni pins is above the charge over-current detection level for a time longer than over-current protection reaction time, the chip activates charge over-current protection. when the charge over-current pr otection is activated, the exte rnal d-fet, pc-fet, and c-fet are disabled and a current protection timer is st arted. this timer ensures that the fets are dis- abled for at least one second. the application software must then set the dfe and cfe bits in the fet control and status register to re-enable normal operation. if the c-fet is re-enabled and the charger continues to supply too high currents, the charge over-current protection will be activated again.
127 2548f?avr?03/2013 atmega406 22.5 short-circuit protection a second level of high current detection is provided to enable a faster response time to very large discharge currents. if a discharge current la rger than the short-circuit detection level is present for a period longer than short-circuit r eaction time, the short-circuit protection is activated. when the short-circuit protection is activated, the external d-fet, pc-fet, and c-fet are dis- abled and a current protection timer is started. this timer ensures that the d-fet, pc-fet, and c-fet are disabled for at least one second. t he application software must then set the dfe and cfe bits in the fet control and status regist er to re-enable normal operation. if the d-fet is re-enabled before the cause of the short-circui t condition is removed, the short-circuit protec- tion will be activated again. the over-current and short-circuit protection parameters are programmable to adapt to different types of batteries. the parameters are set by wr iting to i/o registers. the parameter registers can be locked after the initial configuration, prohibiting any further updates until the next hard- ware reset. refer to ?register description for battery protection? on page 128 for register descriptions. 22.6 battery protection cpu interface the battery protection cpu interface is illustrated in figure 22-1 . figure 22-1. battery protection cpu interface each protection has an interrupt flag. each flag can be read and cleared by the cpu, and each flag has an individual interrupt enable. all enabled flags are comb ined into a single battery pro- tection interrupt request to the cpu. this interrupt can wake up the cpu from any operation mode, except power-off. the interrupt flags are clea red by writing a logic ?1? to their bit locations from the cpu. note that there are neither flags nor status bits indicating that the chip has entered the power off mode. this is because the cpu is powered dow n in this mode. the cpu will, however be able 4 / 4 / 8 / interrupt request interrupt acknowledge fet control current battery protection battery protection control register battery protection timing register battery protection level register battery protection parameter lock register voltage battery protection ppi nni vfet lock? lock? lock? 8-bit data bus deep under-voltage power-off battery protection interrupt register current protection
128 2548f?avr?03/2013 atmega406 to detect that it came from a power-off situation by monitoring cpu reset flags when it resumes operation. 22.7 register description for battery protection the battery protection module operates in a diff erent clock domain than the cpu. whenever a new value is written to bpcr, bpduv, bpocd, bpscd, or cpbtr, the value must be synchro- nized to the battery protection clock domain. s ubsequent writes to this register should not be made during this synchronization. therefore, after writing to one of these registers, the same register should not be re-written within the next 8 cpu clock peri ods. note that each register is synchronized independently of the others. 22.7.1 bpplr ? battery protection parameter lock register ? bit 7:2 ? res: reserved bits these bits are reserved bits in the atmega406 and will always read as zero. ? bit 1 ? bpple: battery protection parameter lock enable ? bit 0 ? bppl: battery protection parameter lock the battery protection parameters set in the ba ttery protection parameter registers and the disable function set in the battery protection disable register can be locked from any further software updates. once locked, these register s cannot be accessed until the next hardware reset. this provides a safe method for protecti ng these registers from unintentional modification by software runaway. it is recommended that softw are sets these registers shortly after reset, and then protects these regist ers from any further updates. to lock these registers, the fo llowing algorithm must be followed: 1. in the same operat ion, write a logic one to bpple and bppl. 2. within the next four clock cyc les, in the same operation. write a logic zero to bpple and a logic one to bppl. the battery protection para meter registers are bpcr, c bptr, bpocp, bpscd and bpduv. 22.7.2 bpcr ? battery protection control register ? bit 7:4 ? res: reserved bits these bits are reserved bits in the atmega406 and will always read as zero. ? bit 3 ? duvd: deep under-voltage protection disable bit 76543210 (0xf8) ??????bpplebpplbpplr read/write rrrrrrr/wr/w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0xf7) ? ? ? ? duvd scd dcd ccd bpcr read/write r r r r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
129 2548f?avr?03/2013 atmega406 when the duvd bit is set, the deep under-voltage protection is disabled. the deep under-volt- age detection will be disabled, and any d eep under-volta ge condition will be ignored ? bit 2 ? scd: short circuit protection disabled when the scd bit is set, the short-circuit protec tion is disabled. the short-circuit detection will be disabled, and any short-circ uit condition will be ignored. ? bit 1 ? dcd: discharge over-current protection disable when the dcd bit is set, the discharge over-current protection is disabled. the discharge over-current detection will be disabled, and any discharge ov er-current c ondition will be ignored. ? bit 0 ? ccd: charge over-current protection disable when the ccd bit is set, the charge over-current protection is disabled. the charge over-cur- rent detection will be disa bled, and any charge over-curre nt condition will be ignored. 22.7.3 cbptr ? current battery protection timing register ? bit 7:4 ? scpt3:0: short-circuit protection timing these bits control the delay of the short-circuit protection. see table 22-2 . ? bit 3:0 ? ocpt3:0: over-current protection timing these bits control the delay of the ch arge and discharge current protection. see table 22-3 . note that the same setting applies to both types of over-c urrent protection. bit 76543210 (0xf6) scpt[3:0] ocpt[3:0] cbptr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 22-2. scpt[3:0] with corresponding short-circuit delay time short-circuit protection reaction time scpt[3:0] typ scpt[3:0] typ scpt[3:0] typ scpt[3:0] typ 0000 61 s 0100 305 s 1000 610 s 1100 1098 s 0001 122 s 0101 366 s 1001 732 s 1101 1220 s 0010 183 s 0110 427 s 1010 854 s 1110 1342 s 0011 244 s 0111 488 s 1011 976 s 1111 1464 s table 22-3. ocpt[3:0] with co rresponding over-current delay time over-current protection reaction time ocpt[3:0] typ ocpt[3:0] typ ocpt[3:0] typ ocpt[3:0] typ 0000 1 ms 0100 8 ms 1000 16 ms 1100 24 ms 0001 2 ms 0101 10 ms 1001 18 ms 1101 26 ms 0010 4 ms 0110 12 ms 1010 20 ms 1110 28 ms 0011 6 ms 0111 14 ms 1011 22 ms 1111 30 ms
130 2548f?avr?03/2013 atmega406 22.7.4 bpocd ? battery protection over-current detection level register ? bits 7:4 ? dcdl3:0: discharge over-current detection level these bits set the r sense voltage level for detection of discharge over-current, as defined in table 22-4 . ? bits 3:0 ? ccdl3:0: charge over-current detection level these bits set the r sense voltage level for detection of charge over-current, as defined in table 22-5 . 22.7.5 bpscd ? battery protection short-circuit detection level register ? bit 7:4 ? res: reserved bits these bits are reserved bits in the atmega406 and will always read as zero. ? bits 3:0 ? scdl3:0: short-circuit detection level these bits set the rsense voltage level for detection of short-circuit in the discharge direction, as defined in table 22-6 on page 131 . bit 76543210 (0xf5) dcdl[3:0] ccdl[3:0] bpocd read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 22-4. dcdl[3:0] with corresponding r sense voltage for discharge over-current detec- tion level discharge over-current protection detection level dcdl[3:0] typ dcdl[3:0] typ dcdl[3:0] typ dcdl[3:0] typ 0000 0.050v 0100 0.070v 1000 0.110v 1100 0.160v 0001 0.055v 0101 0.080v 1001 0.120v 1101 0.180v 0010 0.060v 0110 0.090v 1010 0.130v 1110 0.200v 0011 0.065v 0111 0.100v 1011 0.140v 1111 0.220v table 22-5. ccdl[3:0] with corresponding r sense voltage for charge over-current detection level charge over-current protection detection level ccdl[3:0] typ ccdl[3:0] typ ccdl[3:0] typ ccdl[3:0] typ 0000 0.050v 0100 0.070v 1000 0.110v 1100 0.160v 0001 0.055v 0101 0.080v 1001 0.120v 1101 0.180v 0010 0.060v 0110 0.090v 1010 0.130v 1110 0.200v 0011 0.065v 0111 0.100v 1011 0.140v 1111 0.220v bit 76543210 (0xf4) ? ? ? ? scdl[3:0] bpscd read/write r r r r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
131 2548f?avr?03/2013 atmega406 22.7.6 bpduv ? battery protection deep under voltage register ? bit 7:6 ? res: reserved bits these bits are reserved bits in the atmega406 and will always read as zero. ? bits 5:4 ? duvt1:0: deep under-voltage timing these bits set the deep under-voltage protection delay. ? bits 3:0 ? dudl3:0: deep under-voltage detection level these bits set the deep under-voltage detection level. table 22-6. scdl[3:0] with corresponding r sense voltage for short-circuit detection level short-circuit protection detection level scdl[3:0] typ scdl[3:0] typ scdl[3:0] typ scdl[3:0] typ 0000 0.100v 0100 0.140v 1000 0.220v 1100 0.320v 0001 0.110v 0101 0.160v 1001 0.240v 1101 0.360v 0010 0.120v 0110 0.180v 1010 0.260v 1110 0.400v 0011 0.130v 0111 0.200v 1011 0.280v 1111 0.440v bit 76543210 (0xf3) ? ? duvt[1:0] dudl[3:0] bpduv read/write r r r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 22-7. duvt[1:0] with corresponding deep under-voltage delay duvt1:0 deep under-voltage delay 00 750 ms 01 1000 ms 10 1250 ms 11 1500 ms table 22-8. dudl[3:0] with corresponding deep under-voltage detection level dudl[3:0] typ dudl[3:0] typ 0000 4.71v 1000 7.23v 0001 5.03v 1001 7.54v 0010 5.34v 1010 7.86v 0011 5.66v 1011 8.17v 0100 5.97v 1100 8.49v 0101 6.29v 1101 8.80v 0110 6.60v 1110 9.11v 0111 6.91v 1111 9.43v
132 2548f?avr?03/2013 atmega406 22.7.7 bpir ? battery protection interrupt register ? bit 7 ? duvif: deep under-voltage early warning interrupt flag if the voltage at vfet pin is below the deep under-voltage detection level and only 250 ms is left of the deep under-voltage delay, duvif become s set. the flag must be cleared by writing a logical one to it. ? bit 6 ? cocif: charge over-current protection activated interrupt flag when the charge over-current protection is ac tivated, cocif becomes set. the flag must be cleared by writing a logical one to it. ? bit 5 ? docif: discharge over-current protection activated interrupt flag when the discharge over-current protection is activated, docif becomes set. the flag must be cleared by writing a logical one to it. ? bit 4 ? scif: short-circuit pr otection activated interrupt flag when the short-circuit protection is activated, scif becomes set. the flag must be cleared by writing a logical one to it. ? bit 3 ? duvie: deep under-voltage early warning interrupt enable the duvie bit enables interrupt caused by the deep under-voltage early warning interrupt flag ? bit 2 ? cocie: charge over-current protection activated interrupt enable the cocie bit enables interrupt caused by the charge over-current protection activated inter- rupt flag. ? bit 1 ? docie: discharge over-current protection activated interrupt enable the docie bit enables interrupt caused by the discharge over-current protection activated interrupt flag. ? bit 0 ? scie: short-circuit protection activated interrupt enable the scie bit enables interrupt caused by the shor t-circuit protection ac tivated interrupt flag. if one of the battery protection interrupt flags is set, and the corresponding interrupt enable bit and the i-bit in the status regi ster (sreg) are set, the mcu will jump to the battery protection interrupt vector. the application software must read the battery protection interrupt register to determine the cause of the interrupt. the interrupt flags will not be cleared when the interrupt routine is executed, they must be clea red by writing a logical one to them. bit 76543210 (0xf2) duvif cocif docif scif duvie cocie docie scie bpir read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
133 2548f?avr?03/2013 atmega406 23. fet control in addition to the fet disable control signals from the battery protection circuitry, the cpu may disable the charge fet (c-fet), the discharge fe t (d-fet), or both, by writing to the fet control register. note that the cpu is never allo wed to enable a fet that is disabled by the bat- tery protection circuitry. the fet control is shown in figure 23-1 on page 133 . the pwm output from the 8-bit timer/counter0, oc0b, can be configured to drive the c-fet, precharge fet (pc-fet) or both directly. this can be useful for controlling the charging of the battery cells. the pwm is configured by the com0b1:0 and wgm02:0 bits in the tccr0a/tccr0b registers. note that the oc0b pins does not need to be configured as an out- put. this means that the pwm output can be used to drive the c-fet and/or the pc-fet without occupying the oc0b-pin. if c-fet is disabled and d-fet enabled, discharge current will run through the body-drain diode of the c-fet and vice versa. to avoid the potent ial heat problem from this situation, software must ensure that d-fet is not disabled when a char ge current is flowing, and that c-fet is not disabled when a discharge current is flowing. if the battery has been deeply discharged, large surge currents may result when a charger is connected. in this case, it is recommended to fi rst pre charge the battery through a current limit- ing resistor. for this purpose, atmega406 provid es a precharge fet (pc-fet) control output. this output is default enabled. if atmega406 has entered the po wer-off mode, all fet control outputs will be disabled. when a charger is connected, the cpu will wake up. wh en waking up from power-off mode, the c-fet and d-fet control outputs will rema in disabled while pc-fet is default enabled. when the cpu detects that the cell voltages have risen enough to allow normal charging, it should enable the c-fet and d-fet control outputs and disable the pc-fet control output. if the current battery protection has been activated, the curr ent protection timer will ensure a hold-off time of 1 second before software can re-enable the external fets. figure 23-1. fet control block diagram fet control and status register fet driver fet driver dfe cfe current_protection power-off mode 8-bit data bus oc od current protection timer 1 0 pwmoc oc0b fet driver pfd opc 1 0 pwmopc
134 2548f?avr?03/2013 atmega406 23.1 fet driver figure 23-2. connection of external fets the connection of external fets to od, oc, and opc is shown in figure 23-2 . when switching on an fet, the output pulls the gate quickly low to avoid heating of the fet. when the fet is switched completely on, the outp ut changes operation mode in order to reduce current consumption. the gate-source voltage for the fet when switched on, |v gs_on | , is limited to 13v 15%. when disabling an external fet, the fet driver output quickly pushes the gate voltage to the source pin potential, making the gate-source volt age of the fet close to zero. this disables the fet, and the fet driver output sw itches operation mode to high impedance in order to reduce current consumption. the external resistor wi ll keep the gate-source voltage at zero until the fet is enabled again and its gate is pulled low as explained above. 23.2 register description for fet control the fet controller operates in a different clock domain than the cpu. whenever a new value is written to the fcsr, the value must be synchron ized to the fet controlle r clock domain. subse- quent writes to this register should not be m ade during this synchronization. therefore, after writing to this register, a guard time of 3 ulp oscillator cycles + 3 cpu clock cycles is required. it is recommended that software only reads the fcsr when handling a battery protection inter- rupt (bpint). 23.2.1 fcsr ? fet control and status register ? bits 7:6 ? res: reserved bits these bits are reserved bits in the atmega406, and will always read as zero. ? bit 5 ? pwmoc: pulse width modulation of oc output rcf rdf oc opc od pvt batt rpf rpc + rn bit 76 5 4 3210 (0xf0) ? ? pwmoc pwmopc cps dfe cfe pfd fcsr read/write r r r/w r/w r r/w r/w r/w initial value00 0 0 0000
135 2548f?avr?03/2013 atmega406 when the pwmoc is cleared (zero), the cfe bit and the battery protection circuitry controls the oc output. when this bit is set (one), the oc output will be the logical and of the pwm output from the 8-bit timer/counter0 and the invers e of current_protection from the battery protection circuitry. ? bit 4 ? pwmopc: pulse width modulation of opc output when the pwmopc is cleared (zero), the pfd bit and the battery protecti on circuitry controls the opc output. when this bit is set (one), the opc output will be the l ogical and of the pwm output from the 8-bit timer/ counter0 and the inverse of current_protection from the battery protection circuitry. ? bit 3 ? cps: current protection status the cps bit shows the status of the current prot ection. this bit is se t (one) when the current protection timer is activated, and is clea red (zero) when the hold-off time has elapsed. ? bit 2 ? dfe: discharge fet enable when the dfe bit is cleared (z ero), the discharge fet will be dis abled regardless of the state of the battery protection circuitry. when this bit is set (one), the discharge fet state is determined by the battery protection circui try. this bit will be cleared w hen current_protection is set (one). ? bit 1 ? cfe: charge fet enable when the cfe bit is cleared (zero), the charge fet will be disabled regardless of the state of the battery protection circuitry. when this bit is set (one), the charge fet state is determined by the battery protection circuitry. this bit wi ll be cleared when current_protection is set (one). ? bit 0 ? pfd: precharge fet disable the pfd bit provides complete control of the precharge fet. when the pfd bit is cleared (zero), the precharge fet will be enabled. when the pfd bit is cleared, the precharge fet will be enabled. when the pfd bit is set (one), the prec harge fet will be disabled. this bit will be cleared when the current_protection is set (one)
136 2548f?avr?03/2013 atmega406 24. cell balancing atmega406 incorporates cell balancing fets. the chip provides one cell balancing fet for each battery cell in series. the fets are directly controlled by the applic ation softwa re, allowing the cell balancing algorithms to be implemented in software. the fets are connected in parallel with the individual batter y cells. the cell balancing is illustrated in figure 24-1 . the figure shows a four-cell configuration. the cell balancing fets are disabled in the power-off mode. typical current through the cell balancing fets (t cb ) is 2 ma. the cell balancing fets are controlled by the cbcr. neighbouring fets cannot be simultaneously enabled. if trying to enable two neighbouring fets, both will be disabled. figure 24-1. cell balancing cell balancing control register t cb rp rp rp rp t cb t cb t cb level shift level shift level shift level shift pv1 nv pv2 pv3 pv4 8-bit data bus rp
137 2548f?avr?03/2013 atmega406 24.1 register description 24.1.1 cbcr ? cell balancing control register ? bit 7:4 ? res: reserved bits these bits are reserved bits in the atmega406 and will always read as zero. ? bit 3 ? cbe4: cell balancing enable 4 when this bit is set, the integrated cell ba lancing fet between terminals pv4 and pv3 will be enabled. when the bit is cleared, the cell bala ncing fet will be disabled. the cell balancing fets are always disabled in power-off mo de. cbe4 cannot be set if cbe3 is set. ? bit 2 ? cbe3: cell balancing enable 3 when this bit is set, the integrated cell ba lancing fet between terminals pv3 and pv2 will be enabled. when the bit is cleared, the cell bala ncing fet will be disabled. the cell balancing fets are always disabled in power-off mode. c be3 cannot be set if cbe2 or cbe4 is set. ? bit 1 ? cbe2: cell balancing enable 2 when this bit is set, the integrated cell ba lancing fet between terminals pv2 and pv1 will be enabled. when the bit is cleared, the cell bala ncing fet will be disabled. the cell balancing fets are always disabled in power-off mode. c be2 cannot be set if cbe1 or cbe3 is set. ? bit 0 ? cbe1: cell balancing enable 1 when this bit is set (one), t he integrated cell balancing fet between terminals pv1 and nv will be enabled. when the bit is cleared (zero), th e cell balancing fet will be disabled. the cell bal- ancing fets are always disabled in power-off mode. cbe1 cannot be set if cbe2 is set. bit 76543210 (0xf1) ? ? ? ? cbe4 cbe3 cbe2 cbe1 cbcr read/write r r r r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
138 2548f?avr?03/2013 atmega406 25. 2-wire serial interface 25.1 features ? simple yet powerful and flexible communication interface, only two bus lines needed ? both master and slave operation supported ? device can operate as transmitter or receiver ? 7-bit address space allows up to 128 different slave addresses ? multi-master arbitration support ? operates on 4 mhz clock, achieving up to 100 khz data transfer speed ? slew-rate limited output drivers ? noise suppression circuitry rejects spikes on bus lines ? fully programmable slave address with general call support ? address recognition causes wake-up when avr is in sleep mode 25.2 two-wire serial in terface bus definition the two-wire serial interface (twi) is ideally suited for typical microc ontroller applications. the twi protocol allows the systems designer to in terconnect up to 128 different devices using only two bi-directional bus lines, one for clock (scl) and one for data (sda). the only external hard- ware needed to implement the bus is a single pull- up resistor for each of the twi bus lines. all devices connected to the bus have individual addresses, and mechanisms for resolving bus contention are inherent in the twi protocol. the prtwi bit in ?prr0 ? power reduction register 0? on page 36 must be written to zero to enable twi module. figure 25-1. twi bus interconnection device 1 device 2 device 3 device n sda scl ........ r1 r2 v bus
139 2548f?avr?03/2013 atmega406 25.2.1 twi terminology the following definitions are frequently encountered in this section. 25.2.2 electrical interconnection as depicted in figure 25-1 , both bus lines are connected to the positive supply voltage through pull-up resistors. the bus driver s of all twi-compliant devices are open-drain or open-collector. this implements a wired-and functi on which is essential to the o peration of the interface. a low level on a twi bus line is generated when one or more twi devices output a zero. a high level is output when all twi devices tri-state their outputs, allowing the pull-up resistors to pull the line high. note that all avr devices connected to the twi bus must be powered in order to allow any bus operation. the number of devices that can be connected to the bus is only limited by the bus capacitance limit of 400 pf and the 7-bit slave address space. a detailed specification of the electrical char- acteristics of the twi is given in ?2-wire serial interface characteristics? on page 229 . 25.3 data transfer and frame format 25.3.1 transferring bits each data bit transferred on the twi bus is accompanied by a pulse on the clock line. the level of the data line must be stable when the clock line is high. the only exception to this rule is for generating start and stop conditions. figure 25-2. data validity table 25-1. twi terminology term description master the device that initiates and terminates a transmission. the master also generates the scl clock. slave the device addressed by a master. transmitter the device placing data on the bus. receiver the device reading data from the bus. sda scl data stable data stable data change
140 2548f?avr?03/2013 atmega406 25.3.2 start and stop conditions the master initiates and terminates a data transmission. the trans mission is initiated when the master issues a start condition on the bus, and it is terminated when the master issues a stop condition. between a start and a stop condition, the bus is considered busy, and no other master should try to seize control of t he bus. a special case occurs when a new start condition is issued between a start and stop condition. this is referred to as a repeated start condition, and is used when the master wis hes to initiate a new transfer without relin- quishing control of the bus. after a repeated start, the bus is cons idered busy until the next stop. this is identical to the start behavior, and therefore start is used to describe both start and repeated start for the remainder of this datasheet, unless otherwise noted. as depicted below, start and stop conditions are signalled by changing the level of the sda line when the scl line is high. figure 25-3. start, repeated start, and stop conditions 25.3.3 address packet format all address packets transmitted on the twi bus are nine bits long , consisting of seven address bits, one read/write control bit and an acknowle dge bit. if the read/write bit is set, a read operation is to be performed, otherwise a write operation should be performed. when a slave recognizes that it is being a ddressed, it should acknowledge by pulling sda low in the ninth scl (ack) cycle. if the addressed slave is busy, or for some other reason can not service the mas- ter?s request, the sda line should be left high in the ack clock cycle. the master can then transmit a stop condition, or a repeated start condition to in itiate a new tr ansmission. an address packet consisting of a slave address and a read or a write bit is called sla+r or sla+w, respectively. the msb of the address byte is transmitted first. slave addresses can freely be allocated by the designer, but the address 0000 000 is reserved for a general call. when a general call is issued, all slaves should respond by pulling the sda line low in the ack cycle. a general call is used when a master wi shes to transmit the same message to several slaves in the system. when the general call addre ss followed by a write bit is transmitted on the bus, all slaves set up to ackn owledge the general call will pull th e sda line low in the ack cycle. the following data packets will then be received by all the slaves that acknowle dged the general call. note that transmitting the general call add ress followed by a read bit is meaningless, as this would cause contention if several slaves started transmitting different data. all addresses of the format 1111 xxx should be reserved for future purposes. sda scl start stop repeated start stop start
141 2548f?avr?03/2013 atmega406 figure 25-4. address packet format 25.3.4 data packet format all data packets transmitted on the twi bus are nine bits long, consisting of one data byte and an acknowledge bit. during a data transfer, the master generates the clock and the start and stop conditions, while the receiver is res ponsible for acknowledgi ng the reception. an acknowledge (ack) is signalled by the receiver pulling the sda line low during the ninth scl cycle. if the receiver leaves the sda line high, a nack is signalled. when the receiver has received the last byte, or for some reason cannot receive any more bytes, it should inform the transmitter by sending a nack after the final byte. the msb of the data byte is transmitted first. figure 25-5. data packet format 25.3.5 combining address and data packets into a transmission a transmission basically consists of a start co ndition, a sla+r/w, one or more data packets and a stop condition. an empty message, consisting of a start followed by a stop condi- tion, is illegal. note that the wired-anding of the scl line can be used to implement handshaking between the master and the slave. the slave can extend the scl low period by pulling the scl line low. this is useful if the cloc k speed set up by the master is too fast for the slave, or the slave needs extra time for proces sing between the data transmissions. the slave extending the scl low period will not affect t he scl high period, which is determined by the master. as a consequence, the slave can reduce the twi data transfer speed by prolonging the scl duty cycle. figure 25-6 shows a typical data transmission. note that several data bytes can be transmitted between the sla+r/w and the stop condition, depending on the software protocol imple- mented by the application software. sda scl start 12 789 addr msb addr lsb r/w ack 12 789 data msb data lsb ack aggregate sda sda from transmitter sda from receiver scl from master sla+r/w data byte stop, repeated start, or next data byte
142 2548f?avr?03/2013 atmega406 figure 25-6. typical data transmission 25.4 multi-master bus systems, ar bitration and synchronization the twi protocol allows bus s ystems with several masters. s pecial concerns have been taken in order to ensure that transmis sions will proceed as normal, even if two or more masters initiate a transmission at the same time. two pr oblems arise in mu lti-master systems: ? an algorithm must be implemented allowing only one of the masters to complete the transmission. all other masters should cease tran smission when they discover that they have lost the selection process. this selection pr ocess is called arbitration. when a contending master discovers that it has lost the arbitratio n process, it should immediately switch to slave mode to check whether it is being addressed by the winning master. th e fact that multiple masters have started transmission at the same time should not be detectable to the slaves (i.e., the data being transferred on the bus must not be corrupted). ? different masters may use different scl frequencies. a scheme must be devised to synchronize the serial clocks from all masters, in order to let the transmission proceed in a lockstep fashion. this will fac ilitate the arbitration process. the wired-anding of the bus lines is used to solv e both these problems. the serial clocks from all masters will be wired-anded, yielding a co mbined clock with a high period equal to the one from the master with the shorte st high period. the low period of the combined clock is equal to the low period of the master with the longest low per iod. note that all ma sters listen to the scl line, effectively starting to count their scl high and low time-out periods when the combined scl line goes high or low, respectively. 12 789 data byte data msb data lsb ack sda scl start 12 789 addr msb addr lsb r/w ack sla+r/w stop
143 2548f?avr?03/2013 atmega406 figure 25-7. scl synchronization between multiple masters arbitration is carried out by all masters cont inuously monitoring the sda line after outputting data. if the value read from the sda line does not match the value the master had output, it has lost the arbitration. note that a master can only lose arbitration when it outputs a high sda value while another master outputs a low value. the losing master should immediately go to slave mode, checking if it is being addressed by the winning master. the sda line should be left high, but losing masters are allowed to generate a clock signal until the end of the current data or address packet. arbitration will cont inue until only one master re mains, and this may take many bits. if several masters are trying to address the same slave, ar bitration will cont inue into the data packet. figure 25-8. arbitration between two masters note that arbitration is not allowed between: ? a repeated start condition and a data bit. ? a stop condition and a data bit. ? a repeated start and a stop condition. ta low ta high scl from master a scl from master b scl bus line tb low tb high masters start countin g low period masters start countin g hi g h period sda from master a sda from master b sda line synchronized scl line start master a loses arbitration, sda a sda
144 2548f?avr?03/2013 atmega406 it is the user software?s responsibility to ensur e that these illegal arbi tration conditions never occur. this implies that in multi-master system s, all data transfers must use the same composi- tion of sla+r/w and data packets. in other words: all transmissions must contain the same number of data packets, otherwise the re sult of the arbitration is undefined. 25.5 overview of the twi module the twi module is comprised of several submodules, as shown in figure 25-9 . the shaded reg- isters are accessible through the avr data bus. figure 25-9. overview of the twi module 25.5.1 scl and sda pins these pins interface the avr twi with the rest of the mcu system. the output drivers contain a slew-rate limiter in order to conform to the twi specification. the input stages contain a spike suppression unit removing spikes shorter than 50 ns. twi unit address register (twar) address match unit address comparator control unit status register (twsr) state machine and status control scl slew-rate control spike filter sda slew-rate control spike filter bit rate generator bit rate register (twbr) prescaler bus interface unit start / stop control arbitration detection ack spike suppression address/data shift register (twdr) control register (twcr)
145 2548f?avr?03/2013 atmega406 25.5.2 bit rate generator unit this unit controls the period of scl when oper ating in a master mode. the scl period is con- trolled by settings in the twi bit rate register (twbr) and the prescaler bits in the twi status register (twsr). slave operation does not depend on bit rate or prescaler settings, but the cpu clock frequency in the slave must be at least 16 times higher than the scl frequency. note that slaves may prolong the scl low period, thereby reducing the average twi bus clock period. the scl frequency is generated according to the following equation: ? twbr = value of the twi bit rate register. ? twps = value of the prescaler bits in the twi status register. notes: 1. twbr should be 10 or higher if the twi oper ates in master mode. if twbr is lower than 10, the master may produce an incorrect output on sda and scl for the reminder of the byte. the problem occurs when operating the twi in ma ster mode, sending start + sla + r/w to a slave (a slave does not need to be connec ted to the bus for the condition to happen). 2. the twi clock is 4 mhz, see ?calibrated fast rc oscillator? on page 26. 25.5.3 bus interface unit this unit contains the data and address shif t register (twdr), a start/stop controller and arbitration detection hardware. the twdr contains the address or data bytes to be transmitted, or the address or data bytes received. in additi on to the 8-bit twdr, the bus interface unit also contains a register containing th e (n)ack bit to be transmitted or received. this (n)ack regis- ter is not directly accessible by the application software. however, when re ceiving, it can be set or cleared by manipulating the twi control r egister (twcr). when in transmitter mode, the value of the received (n)ack bit can be determined by the value in the twsr. the start/stop controller is responsible for gene ration and dete ction of start, repeated start, and stop conditions. th e start/stop controller is able to detect start and stop conditions even when the avr mcu is in one of the sleep modes, enabling the mcu to wake up if addressed by a master. if the twi has initiated a transmission as mast er, the arbitration detection hardware continu- ously monitors the transmission trying to determi ne if arbitration is in process. if the twi has lost an arbitration, the control unit is informed. correct action can then be taken and appropriate status codes generated. 25.5.4 address match unit the address match unit checks if received ad dress bytes match the 7-bit address in the twi address register (twar). if the twi general call recognition enable (twgce) bit in the twar is written to one, all incoming address bits will also be compared against the general call address. upon an address match, the control unit is informed, allowing correct action to be taken. the twi may or may not acknowledge it s address, depending on settings in the twcr. the address match unit is able to compare addresses even when the avr mcu is in sleep mode, enabling the mcu to wake-up if addressed by a master. scl frequency twi clock frequency 16 2(twbr) 4 twps ? + ----------------------------------------------------------- =
146 2548f?avr?03/2013 atmega406 25.5.5 control unit the control unit monitors the twi bus and generates responses corresponding to settings in the twi control register (twcr). when an event requiring the attention of the application occurs on the twi bus, the twi interrupt flag (twint) is asserted. in the next clock cycle, the twi sta- tus register (twsr) is updated with a stat us code identifying the event. the twsr only contains relevant status information when the twi interrupt flag is asserted. at all other times, the twsr contains a special stat us code indicating that no relevant status information is avail- able. as long as the twint flag is set, the scl line is held low. this allows the application software to complete its tasks before a llowing the twi transmission to continue. the twint flag is set in the following situations: ? after the twi has transmitted a start/repeated start condition. ? after the twi has transmitted sla+r/w. ? after the twi has transmitted an address byte. ? after the twi has lost arbitration. ? after the twi has been addressed by own slave address or general call. ? after the twi has received a data byte. ? after a stop or repeated start has been received while still addressed as a slave. ? when a bus error has occu rred due to an illegal st art or stop condition.
147 2548f?avr?03/2013 atmega406 25.6 twi register description 25.6.1 twbr ? twi bit rate register ? bits 7:0 ? twi bit rate register twbr selects the division factor for the bit rate generator. the bit rate generator is a frequency divider which generates the scl clock frequency in the master modes. see ?bit rate generator unit? on page 145 for calculating bit rates. 25.6.2 twcr ? twi control register the twcr is used to control the operation of the twi. it is used to enable the twi, to initiate a master access by applying a start condition to the bus, to generate a receiver acknowledge, to generate a stop condition, and to control haltin g of the bus while the data to be written to the bus are written to the twdr. it also indicates a write collision if data is attempte d written to twdr while the regist er is inaccessible. ? bit 7 ? twint: twi interrupt flag this bit is set by hardware when the twi has finished its current job and expects application software response. if the i-bit in sreg and tw ie in twcr are set, the mcu will jump to the twi interrupt vector. while the twint flag is se t, the scl low period is stretched. the twint flag must be cleared by software by writing a logic one to it. note that this flag is not automati- cally cleared by hardware when executing the interr upt routine. also note that clearing this flag starts the operation of the twi, so all access es to the twi address register (twar), twi sta- tus register (twsr), and twi data register (twdr) must be complete before clearing this flag. ? bit 6 ? twea: twi enable acknowledge bit the twea bit controls the generation of the ac knowledge pulse. if the twea bit is written to one, the ack pulse is generated on the tw i bus if the following conditions are met: 1. the device?s own slave add ress has been received. 2. a general call has been received, while the twgce bit in the twar is set. 3. a data byte has been received in master receiver or slave receiver mode. by writing the twea bit to zero, the device can be virtually disconnected from the two-wire serial bus temporarily. address recognition can then be resumed by writing the twea bit to one again. ? bit 5 ? twsta: twi start condition bit the application writes the twsta bit to one w hen it desires to become a master on the two- wire serial bus. the twi hardware checks if th e bus is available, and generates a start con- bit 76543210 (0xb8) twbr7 twbr6 twbr5 twbr4 twbr3 twbr2 twbr1 twbr0 twbr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 (0xbc) twint twea twsta twsto twwc twen ? twie twcr read/write r/w r/w r/w r/w r r/w r r/w initial value 0 0 0 0 0 0 0 0
148 2548f?avr?03/2013 atmega406 dition on the bus if it is free. however, if the bus is not free, t he twi waits until a stop condition is detected, and then generates a new start co ndition to claim the bus master status. twsta is cleared by the twi hardware when th e start condition has been transmitted. ? bit 4 ? twsto: twi stop condition bit writing the twsto bit to one in master mode will generate a stop condition on the two-wire serial bus. when the stop c ondition is executed on the bus, the twsto bit is cleared auto- matically. in slave mode, setting the twsto bit can be used to recover from an error condition. this will not generate a stop co ndition, but the twi returns to a well-defined unaddressed slave mode and releases the scl and sda lines to a high impedance state. ? bit 3 ? twwc: twi write collision flag the twwc bit is set when attempting to write to the twi data register ? twdr when twint is low. this flag is cleare d by writing the twdr register when twint is high. ? bit 2 ? twen: twi enable bit the twen bit enables twi operation and activate s the twi interface. wh en twen is written to one, the twi takes control over the i/o pins connected to the scl and sda pins, enabling the slew-rate limiters and spike filters. if this bit is written to zero, the twi is switched off and all twi transmissions are terminated, regardless of any ongoing operation. ? bit 1 ? res: reserved bit this bit is a reserved bit an d will always read as zero. ? bit 0 ? twie: twi interrupt enable when this bit is written to one, and the i-bit in sreg is set, th e twi interrupt request will be acti- vated for as long as the twint flag is high. 25.6.3 twsr ? twi status register ? bits 7:3 ? tws: twi status these five bits reflect the status of the twi lo gic and the two-wire serial bus. the different sta- tus codes are described in table 25-3 on page 156 through table 25-6 on page 165 . note that the value read from twsr contains both the 5-bi t status value and the 2-bit prescaler value. the application designer should mask the prescaler bi ts to zero when checking the status bits. this makes status checking independent of prescaler setting. this approach is used in this data- sheet, unless otherwise noted. ? bit 2 ? res: reserved bit this bit is reserved and will always read as zero. ? bits 1:0 ? twps: twi prescaler bits these bits can be read and written, and control the bit rate prescaler. bit 76543210 (0xb9) tws7 tws6 tws5 tws4 tws3 ? twps1 twps0 twsr read/write rrrrrrr/wr/w initial value 1 1 1 1 1 0 0 0
149 2548f?avr?03/2013 atmega406 to calculate bit rates, see ?bit rate generator unit? on page 145 . the value of twps1:0 is used in the equation. 25.6.4 twdr ? twi data register in transmit mode, twdr contains the next byte to be transmitted. in receive mode, the twdr contains the last byte received. it is writable while the twi is not in the process of shifting a byte. this occurs when the twi interrupt flag (twint) is set by hardware. note that the data register cannot be initialized by the user before the fi rst interrupt occurs. the data in twdr remains sta- ble as long as twint is set. while data is shif ted out, data on the bus is simultaneously shifted in. twdr always contains the last byte presen t on the bus, except after a wake-up from a sleep mode by the twi interrupt. in this case, the conten ts of twdr is undefined. in the case of a lost bus arbitration, no data is lost in the transition from master to slave. handling of the ack bit is controlled automatically by t he twi logic, the cpu cannot access the ack bit directly. ? bits 7:0 ? twd: twi data register these eight bits constitute the next data byte to be transmitted, or the latest data byte received on the two-wire serial bus. 25.6.5 twar ? twi (slave) address register the twar should be loaded with the 7-bit slav e address (in the seven most significant bits of twar) to which the twi will respond when prog rammed as a slave transmitter or receiver, and not needed in the master modes. in multi-master systems, twar must be set in masters which can be addressed as sl aves by other masters. the lsb of twar is used to enable recognition of the general call address (0x00). there is an associated address comparator that looks for the slave address (or general call address if enabled) in the received serial address. if a ma tch is found, an interrupt request is generated. ? bits 7:1 ? twa: twi (slave) address register these seven bits constitute the slave address of the twi unit. table 25-2. twi bit rate prescaler twps1 twps0 prescaler value 00 1 01 4 10 16 11 64 bit 76543210 (0xbb) twd7 twd6 twd5 twd4 twd3 twd2 twd1 twd0 twdr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 1 1 1 1 1 1 1 1 bit 76543210 (0xba) twa6 twa5 twa4 twa3 twa2 twa1 twa0 twgce twar read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 1 1 1 1 1 1 1 0
150 2548f?avr?03/2013 atmega406 ? bit 0 ? twgce: twi general call recognition enable bit if set, this bit enables the recognition of a general call given over the two-wire serial bus. 25.6.6 twamr ? twi (slave) address mask register ? bits 7:1 ? twam: twi address mask the twamr can be loaded with a 7-bit slave addr ess mask. each of the bits in twamr can mask (disable) the corresponding address bits in the twi address register (twar). if the mask bit is set to one then the address match l ogic ignores the compare between the incoming address bit and the corresponding bit in twar. figure 25-10 shown the address match logic in detail. figure 25-10. twi address match logic, block diagram ? bit 0 ? res: reserved bit this bit is an unused bit in the at mega406, and will always read as zero. 25.7 using the twi the avr twi is byte-oriented and interrupt based. interrupts are issued after all bus events, like reception of a byte or transmission of a start condition. because the twi is interrupt-based, the application software is free to carry on othe r operations during a twi byte transfer. note that the twi interrupt enable (twie) bit in twcr to gether with the global interrupt enable bit in sreg allow the application to decide whether or not assertion of the twint flag should gener- ate an interrupt request. if the twie bit is cl eared, the application must poll the twint flag in order to detect actions on the twi bus. when the twint flag is asserted, the twi has finished an operation and awaits application response. in this case, the twi status register (twsr) contains a value indicating the current state of the twi bus. the application software can then decide how the twi should behave in the next twi bus cycle by manipulating the twcr and twdr registers. figure 25-11 is a simple example of how the application can interface to the twi hardware. in this example, a master wishes to transmit a single data byte to a slave. this description is quite abstract, a more detailed explanat ion follows later in th is section. a simple code example imple- menting the desired behavior is also presented. bit 76543210 (0xbd) twam[6:0] ?twamr read/write r/w r/w r/w r/w r/w r/w r/w r initial value 0 0 0 0 0 0 0 0 addre ss match address bit comparator 0 address bit comparator 6..1 twar0 twamr0 address bit 0
151 2548f?avr?03/2013 atmega406 figure 25-11. interfacing the application to the twi in a typical transmission 1. the first step in a twi transmission is to transmit a start condition. this is done by writing a specific value into twcr, instructing the twi ha rdware to transmit a start condition. which value to write is described la ter on. however, it is important that the twint bit is set in the value written. writin g a one to twint clears the flag. the twi will not start any operation as long as the twint bit in twcr is set. immediately after the application has cleared twint, the twi will init iate transmission of the start condition. 2. when the start condition has been transmitted, the twint flag in twcr is set, and twsr is updated with a status code indica ting that the start condition has success- fully been sent. 3. the application software should now examine the value of twsr, to make sure that the start condition was successfully transmitted. if twsr indicates otherwise, the applica- tion software might take some special action, like calling an error routine. assuming that the status code is as expected, the applic ation must load sla+w into twdr. remember that twdr is used both for address and data. after twdr has been loaded with the desired sla+w, a specific value must be wr itten to twcr, instructing the twi hardware to transmit the sla+w present in twdr. wh ich value to write is described later on. however, it is important that the twint bit is set in the value written. writing a one to twint clears the flag. the twi will not start any operation as long as the twint bit in twcr is set. immediately after the applicat ion has cleared twint, the twi will initiate transmission of the address packet. 4. when the address packet has been transmi tted, the twint flag in twcr is set, and twsr is updated with a status code indicating that the address packet has successfully been sent. the stat us code will also reflect whether a slave acknowledge d the packet or not. 5. the application software should now examine the value of twsr, to make sure that the address packet was successfully transmitted, and that the value of the ack bit was as expected. if twsr indicates otherwise, the application software might take some special action, like calling an error rout ine. assuming that the status code is as expected, the application must load a data packet into tw dr. subsequently, a specific value must be written to twcr, instructing the twi hardware to transmit the data packet present in twdr. which value to write is described late r on. however, it is important that the twint bit is set in the value written. writin g a one to twint clears the flag. the twi will start sla+w a data a stop 1. application writes to twcr to initiate transmission of start 2. twint set. status code indicates start condition sent 4. twint set. status code indicates sla+w sent, ack received 6. twint set. status code indicates data sent, ack received 3. check twsr to see if start was sent. application loads sla+w into twdr, and loads appropriate control signals into twcr, making sure that twint is written to one 5. check twsr to see if sla+w was sent and ack received. application loads data into twdr, and loads appropriate control signals into twcr, making sure that twint is written to one 7. check twsr to see if data was sent and ack received. application loads appropriate control signals to send stop into twcr, making sure that twint is written to one twi bus indicates twint set application action twi hardware action
152 2548f?avr?03/2013 atmega406 not start any operation as long as the twint bit in twcr is set. immediately after the application has cleared twint, the twi will in itiate transmission of the data packet. 6. when the data packet has been transmitted, the twint flag in twcr is set, and twsr is updated with a status code indicating th at the data packet has successfully been sent. the status code will also reflect whether a slave acknowledged the packet or not. 7. the application software should now examine the value of twsr, to make sure that the data packet was successfully transmitted, and that the value of the ack bit was as expected. if twsr indicates otherwise, the application software might take some special action, like calling an error rout ine. assuming that the status code is as expected, the application must write a specif ic value to twcr, instructing the twi hardware to transmit a stop condition. which value to write is described later on. ho wever, it is important that the twint bit is set in the value written. wr iting a one to twint clears the flag. the twi will not start any operation as long as the tw int bit in twcr is set. immediately after the application has cleared twint, the twi will initiate transmission of the stop condi- tion. note that twint is not set af ter a stop condition has been sent. even though this example is simple, it shows t he principles involved in all twi transmissions. these can be summarized as follows: ? when the twi has finished an operation and expects application response, the twint flag is set. the scl line is pulled low until twint is cleared. ? when the twint flag is set, the user must upda te all twi registers with the value relevant for the next twi bus cycle. as an example, twdr mu st be loaded with the value to be transmitted in the next bus cycle. ? after all twi register upda tes and other pendi ng application software tasks have been completed, twcr is writ ten. when writing twcr, the twint bit should be set. writing a one to twint clears the flag. t he twi will then commence execut ing whatever operation was specified by the twcr setting. in the following an assembly and c implementation of the example is give n. note that the code below assumes that several definitions have been made for example by using include-files. assembly code example (1) c example (1) comments 1 ldi r16, (1< 153 2548f?avr?03/2013 atmega406 note: 1. see ?about code examples? on page 7 . 25.8 transmission modes the twi can operate in one of four major m odes. these are named master transmitter (mt), master receiver (mr), slave transmitter (st) and slave receiver (sr). several of these modes can be used in the same application. as an example, the twi can use mt mode to write data into a twi eeprom, mr mode to read the data back from the eeprom. if other masters are present in the system, some of these mi ght transmit data to t he twi, and then sr mode would be used. it is the application softw are that decides which modes are legal. the following sections describe each of these modes. possible status codes are described along with figures detailing data transmission in each of the modes. these figures contain the following abbreviations: 4 ldi r16, sla_w out twdr, r16 ldi r16, (1< 154 2548f?avr?03/2013 atmega406 s : start condition rs : repeated start condition r : read bit (high level at sda) w : write bit (low level at sda) a : acknowledge bit (low level at sda) a : not acknowledge bit (high level at sda) data : 8-bit data byte p : stop condition sla : slave address in figure 25-13 to figure 25-19 , circles are used to indicate that the twint flag is set. the num- bers in the circles show the status code held in twsr, with the prescaler bits masked to zero. at these points, actions must be taken by the applic ation to continue or complete the twi transfer. the twi transfer is suspended until th e twint flag is cleared by software. when the twint flag is set, the st atus code in twsr is used to determine the appropriate soft- ware action. for each status code, the required so ftware action and details of the following serial transfer are given in table 25-3 to table 25-6 . note that the prescaler bits are masked to zero in these tables. 25.8.1 master transmitter mode in the master transmitter mode, a number of da ta bytes are transmitted to a slave receiver (see figure 25-12 ). in order to enter a master mode, a start condition must be transmitted. the for- mat of the following address packet determines whether master transmitter or master receiver mode is to be entered. if sla+w is transmitte d, mt mode is entered, if sla+r is transmitted, mr mode is entered. all the st atus codes mentioned in this se ction assume that the prescaler bits are zero or are masked to zero. figure 25-12. data transfer in mast er transmitter mode device 1 master transmitter device 2 slave receiver device 3 device n sda scl ........ r1 r2 v bus
155 2548f?avr?03/2013 atmega406 a start condition is sent by wr iting the following value to twcr: twen must be set to enable the two-wire seri al interface, twsta must be written to one to transmit a start condition and twint must be written to one to clear the twint flag. the twi will then test the two-wire serial bus and gene rate a start condition as soon as the bus becomes free. after a start condition has been transmitted, the twint flag is set by hard- ware, and the status code in twsr will be 0x08 (see table 25-3 ). in order to enter mt mode, sla+w must be transmitted. this is done by writing sla+w to twdr. thereafter the twint bit should be cleared (by writing it to one) to continue the transfer. this is accomplished by writing the following value to twcr: when sla+w have been transmitted and an ack nowledgment bit has been received, twint is set again and a number of status codes in twsr are possible. possible status codes in master mode are 0x18, 0x20, or 0x38. the appropriate action to be taken for each of these status codes is detailed in table 25-3 . when sla+w has been successfully transmitted, a data packet should be transmitted. this is done by writing the data byte to twdr. twdr must only be writ ten when twint is high. if not, the access will be discarded, and the write collision bit (twwc) will be set in the twcr regis- ter. after updating twdr, the twint bit should be cleared (by writing it to one) to continue the transfer. this is acco mplished by writing the following value to twcr: this scheme is repeated until the last byte ha s been sent and the transfer is ended by generat- ing a stop condition or a repeated start conditio n. a stop condition is generated by writing the following value to twcr: a repeated start condition is generated by writing the following value to twcr: after a repeated start condition (state 0x10) the two-wire serial interface can access the same slave again, or a new slave without transmitting a stop c ondition. repeated start enables the master to switch between slaves, master transmitter mode and master receiver mode without losing control of the bus. twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x00 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x00 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x01 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x
156 2548f?avr?03/2013 atmega406 table 25-3. status codes for master transmitter mode status code (twsr) prescaler bits are 0 status of the two-wire serial bus and two-wire serial inter- face hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twint twea 0x08 a start condition has been transmitted load sla+w x 0 1 x sla+w will be transmitted; ack or not ack will be received 0x10 a repeated start condition has been transmitted load sla+w or load sla+r x x 0 0 1 1 x x sla+w will be transmitted; ack or not ack will be received sla+r will be transmitted; logic will switch to master receiver mode 0x18 sla+w has been transmitted; ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x20 sla+w has been transmitted; not ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x28 data byte has been transmit- ted; ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x30 data byte has been transmit- ted; not ack has been received load data byte or no twdr action or no twdr action or no twdr action 0 1 0 1 0 0 1 1 1 1 1 1 x x x x data byte will be transmitted and ack or not ack will be received repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x38 arbitration lost in sla+w or data bytes no twdr action or no twdr action 0 1 0 0 1 1 x x two-wire serial bus will be released and not ad- dressed slave mode entered a start condition will be transmitted when the bus becomes free
157 2548f?avr?03/2013 atmega406 figure 25-13. formats and states in the master transmitter mode 25.8.2 master receiver mode in the master receiver mode, a number of data bytes are received from a slave transmitter (see figure 25-14 ). in order to enter a master mode, a start condition must be transmitted. the for- mat of the following address packet determines whether master transmitter or master receiver mode is to be entered. if sla+w is transmitte d, mt mode is entered, if sla+r is transmitted, mr mode is entered. all the st atus codes mentioned in this se ction assume that the prescaler bits are zero or are masked to zero. s sla w a data a p $08 $18 $28 r sla w $10 ap $20 p $30 a or a $38 a other master continues a or a $38 other master continues r a $68 other master continues $78 $b0 to corresponding states in slave mode mt mr successfull transmission to a slave receiver next transfer started with a repeated start condition not acknowledge received after the slave address not acknowledge received after a data byte arbitration lost in slave address or data byte arbitration lost and addressed as slave data a n from master to slave from slave to master any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the p rescaler bits are zero or masked to zero s
158 2548f?avr?03/2013 atmega406 figure 25-14. data transfer in ma ster receiver mode a start condition is sent by wr iting the following value to twcr: twen must be written to one to enable the tw o-wire serial interface, twsta must be written to one to transmit a start condit ion and twint must be set to clear the twint flag. the twi will then test the two-wire serial bus and generate a start condition as soon as the bus becomes free. after a start condition has been transmitted, the twint flag is set by hardware, and the status code in twsr will be 0x08 (see table 25-3 ). in order to enter mr mode, sla+r must be transmitted. this is done by writing sla+r to twdr. thereafter the twint bit should be cleared (by writing it to one) to continue the tr ansfer. this is accomplis hed by writing the follow- ing value to twcr: when sla+r have been transmitted and an acknow ledgment bit has been received, twint is set again and a number of status codes in twsr are possible. possible status codes in master mode are 0x38, 0x40, or 0x48. the appropriate action to be taken for each of these status codes is detailed in table 25-13 . received data can be read from the twdr register when the twint flag is set high by hardware. this scheme is repe ated until the last byte has been received. after the last byte has been received, the mr should inform the st by sending a nack after the last received data byte. the transfer is ended by generating a stop condition or a repeated start condition. a stop condition is generated by writing the following value to twcr: a repeated start condition is generated by writing the following value to twcr: after a repeated start condition (state 0x10) the two-wire serial interface can access the same slave again, or a new slave without transmitting a stop c ondition. repeated start twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x00 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x01 x1 0 x twcr twint twea twsta twsto twwc twen ? twie value 1 x10 x1 0 x device 1 master receiver device 2 slave transmitter device 3 device n sda scl ........ r1 r2 v bus
159 2548f?avr?03/2013 atmega406 enables the master to switch between slaves, master transmitter mode and master receiver mode without losing control over the bus. table 25-4. status codes for ma ster receiver mode status code (twsr) prescaler bits are 0 status of the two-wire serial bus and two-wire serial inter- face hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twint twea 0x08 a start condition has been transmitted load sla+r x 0 1 x sla+r will be transmitted ack or not ack will be received 0x10 a repeated start condition has been transmitted load sla+r or load sla+w x x 0 0 1 1 x x sla+r will be transmitted ack or not ack will be received sla+w will be transmitted logic will switch to master transmitter mode 0x38 arbitration lost in sla+r or not ack bit no twdr action or no twdr action 0 1 0 0 1 1 x x two-wire serial bus will be released and not ad- dressed slave mode will be entered a start condition will be transmitted when the bus becomes free 0x40 sla+r has been transmitted; ack has been received no twdr action or no twdr action 0 0 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x48 sla+r has been transmitted; not ack has been received no twdr action or no twdr action or no twdr action 1 0 1 0 1 1 1 1 1 x x x repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset 0x50 data byte has been received; ack has been returned read data byte or read data byte 0 0 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x58 data byte has been received; not ack has been returned read data byte or read data byte or read data byte 1 0 1 0 1 1 1 1 1 x x x repeated start will be transmitted stop condition will be transmitted and twsto flag will be reset stop condition followed by a start condition will be transmitted and twsto flag will be reset
160 2548f?avr?03/2013 atmega406 figure 25-15. formats and states in the master receiver mode 25.8.3 slave receiver mode in the slave receiver mode, a number of data by tes are received from a master transmitter (see figure 25-16 ). all the status codes mentio ned in this section assume that the prescaler bits are zero or are masked to zero. figure 25-16. data transfer in slave receiver mode to initiate the slave receiver mode, twar and twcr must be initialized as follows: s sla r a data a $08 $40 $50 sla r $10 ap $48 a or a $38 other master continues $38 other master continues w a $68 other master continues $78 $b0 to corresponding states in slave mode mr mt successfull reception from a slave receiver next transfer started with a repeated start condition not acknowledge received after the slave address arbitration lost in slave address or data byte arbitration lost and addressed as slave data a n from master to slave from slave to master any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the p rescaler bits are zero or masked to zero p data a $58 a r s device 3 device n sda scl ........ r1 r2 v bus device 2 master transmitter device 1 slave receiver
161 2548f?avr?03/2013 atmega406 the upper seven bits are the address to which t he two-wire serial interface will respond when addressed by a master. if the lsb is set, the tw i will respond to the general call address (0x00), otherwise it will ignore the general call address. twen must be written to one to enable the twi. the twea bit must be written to one to enable the acknowledgment of the devic e?s own slave address or the general call address. twsta and twsto must be written to zero. when twar and twcr have been initialized, the twi waits until it is addressed by its own slave address (or the general call address if enabled) followed by the data direction bit. if the direction bit is ?0? (write), the twi will operate in sr mode, otherwise st mode is entered. after its own slave address and the write bit have been received, the twint flag is set and a valid status code can be read from twsr. the status c ode is used to determine the appropriate soft- ware action. the appropriate action to be taken for each status code is detailed in table 25-5 . the slave receiver mode may also be entered if ar bitration is lost while the twi is in the master mode (see states 0x68 and 0x78). if the twea bit is reset during a transfer, the tw i will return a ?not acknowledge? (?1?) to sda after the next received data byte. this can be us ed to indicate that t he slave is not able to receive any more bytes. while twea is zero, the twi does not acknowledge its own slave address. however, the two-wire serial bus is still monitored and address recognition may resume at any time by setting twea. this implies that the twea bit may be used to temporarily isolate the twi from the two-wire serial bus. in all sleep modes other than idle mode, the clo ck system to the twi is turned off. if the twea bit is set, the interface can still acknowledge its own slave ad dress or the general call address by using the two-wire serial bus clock as a clock source. the part will then wake-up from sleep and the twi will hold the scl clock low during the wake up and until the twint flag is cleared (by writing it to one). further data reception will be carri ed out as normal, with the avr clocks running as normal. observe that if the avr is se t up with a long start-up time, the scl line may be held low for a long time, bl ocking other data transmissions. note that the two-wire serial interface data register ? twdr does not reflect the last byte present on the bus when waking up from these sleep modes. twar twa6 twa5 twa4 twa3 twa2 twa1 twa0 twgce value device?s own slave address twcr twint twea twsta twsto twwc twen ? twie value 0 100 01 0 x
162 2548f?avr?03/2013 atmega406 table 25-5. status codes for slave receiver mode status code (twsr) prescaler bits are 0 status of the two-wire serial bus and two-wire serial interface hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twint twea 0x60 own sla+w has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x68 arbitration lost in sla+r/w as master; own sla+w has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x70 general call address has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x78 arbitration lost in sla+r/w as master; general call address has been received; ack has been returned no twdr action or no twdr action x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x80 previously addressed with own sla+w; data has been received; ack has been returned read data byte or read data byte x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x88 previously addressed with own sla+w; data has been received; not ack has been returned read data byte or read data byte or read data byte or read data byte 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free 0x90 previously addressed with general call; data has been re- ceived; ack has been returned read data byte or read data byte x x 0 0 1 1 0 1 data byte will be received and not ack will be returned data byte will be received and ack will be returned 0x98 previously addressed with general call; data has been received; not ack has been returned read data byte or read data byte or read data byte or read data byte 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free 0xa0 a stop condition or repeated start condition has been received while still addressed as slave read data byte or read data byte or read data byte or read data byte 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free
163 2548f?avr?03/2013 atmega406 figure 25-17. formats and states in the slave receiver mode s sla w a data a $60 $80 $88 a $68 reception of the own slave address and one or more data bytes. all are acknowledged last data byte received is not acknowledged arbitration lost as master and addressed as slave reception of the general call address and one or more data bytes last data byte received is not acknowledged n from master to slave from slave to master any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the prescaler bits are zero or masked to zero p or s data a $80 $a0 p or s a a data a $70 $90 $98 a $78 p or s data a $90 $a0 p or s a general call arbitration lost as master and addressed as slave by general call data a
164 2548f?avr?03/2013 atmega406 25.8.4 slave transmitter mode in the slave transmitter mode, a number of data bytes are transmitted to a master receiver (see figure 25-18 ). all the status codes mentio ned in this section assume that the prescaler bits are zero or are masked to zero. figure 25-18. data transfer in slave transmitter mode to initiate the slave transmitter mode, twar and twcr must be in itialized as follows: the upper seven bits are the address to which t he two-wire serial interface will respond when addressed by a master. if the lsb is set, the tw i will respond to the general call address (0x00), otherwise it will ignore the general call address. twen must be written to one to enable the twi. the twea bit must be written to one to enable the acknowledgment of the devic e?s own slave address or the general call address. twsta and twsto must be written to zero. when twar and twcr have been initialized, the twi waits until it is addressed by its own slave address (or the general call address if enabled) followed by the data direction bit. if the direction bit is ?1? (read), the twi will operate in st mode, otherw ise sr mode is entered. after its own slave address and the write bit have been received, the twint flag is set and a valid status code can be read from twsr. the status c ode is used to determine the appropriate soft- ware action. the appropriate action to be taken for each status code is detailed in table 25-6 . the slave transmitter mode may also be entered if arbitration is lost while the twi is in the master mode (see state 0xb0). if the twea bit is written to zero during a transfer, the twi will transm it the last byte of the trans- fer. state 0xc0 or state 0xc8 will be entered, depending on whethe r the master receiver transmits a nack or ack after the final byte. the twi is switched to the not addressed slave mode, and will ignore the master if it continues the transfer. thus the master receiver receives all ?1? as serial data. state 0xc8 is entered if the master demands additional data bytes (by transmitting ack), even though the slave has tran smitted the last byte (twea zero and expect- ing nack from the master). twar twa6 twa5 twa4 twa3 twa2 twa1 twa0 twgce value device?s own slave address twcr twint twea twsta twsto twwc twen ? twie value 0 100 01 0 x device 3 device n sda scl ........ r1 r2 v bus device 2 master receiver device 1 slave transmitter
165 2548f?avr?03/2013 atmega406 while twea is zero, the twi does not respond to its own slave address. however, the two-wire serial bus is still monitored an d address recognition may resume at any time by setting twea. this implies that the twea bit may be used to temporarily isolate the twi from the two-wire serial bus. in all sleep modes other than idle mode, the clo ck system to the twi is turned off. if the twea bit is set, the interface can still acknowledge its own slave ad dress or the general call address by using the two-wire serial bus clock as a clock so urce. the part will then wake up from sleep and the twi will hold the scl clock will low during the wake up and until the twint flag is cleared (by writing it to one). further data tr ansmission will be carried out as normal, with the avr clocks running as normal. observe that if the avr is set up with a long start-up time, the scl line may be held low for a long ti me, blocking other data transmissions. note that the two-wire serial interface data register ? twdr ? does not reflect the last byte present on the bus when waking up from these sleep modes. table 25-6. status codes for slave transmitter mode status code (twsr) prescaler bits are 0 status of the two-wire serial bus and two-wire serial interface hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twint twea 0xa8 own sla+r has been received; ack has been returned load data byte or load data byte x x 0 0 1 1 0 1 last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be re- ceived 0xb0 arbitration lost in sla+r/w as master; own sla+r has been received; ack has been returned load data byte or load data byte x x 0 0 1 1 0 1 last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be re- ceived 0xb8 data byte in twdr has been transmitted; ack has been received load data byte or load data byte x x 0 0 1 1 0 1 last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be re- ceived 0xc0 data byte in twdr has been transmitted; not ack has been received no twdr action or no twdr action or no twdr action or no twdr action 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free 0xc8 last data byte in twdr has been transmitted (twea = ?0?); ack has been received no twdr action or no twdr action or no twdr action or no twdr action 0 0 1 1 0 0 0 0 1 1 1 1 0 1 0 1 switched to the not addressed slave mode; no recognition of own sla or gca switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1? switched to the not addressed slave mode; no recognition of own sla or gca; a start condition will be transmitted when the bus becomes free switched to the not addressed slave mode; own sla will be recognized; gca will be recognized if twgce = ?1?; a start condition will be transmitted when the bus becomes free
166 2548f?avr?03/2013 atmega406 figure 25-19. formats and states in the slave transmitter mode 25.8.5 miscellaneous states there are two status codes that do not correspond to a defined twi state, see table 25-7 . status 0xf8 indicates that no relevant information is available because the twint flag is not set. this occurs between other states, and when the twi is not involved in a serial transfer. status 0x00 indicates that a bus error has occu rred during a two-wire serial bus transfer. a bus error occurs when a start or stop condition occu rs at an illegal position in the format frame. examples of such illegal positions are during the serial transfer of an address byte, a data byte, or an acknowledge bit. when a bus error occurs, twint is set. to recover from a bus error, the twsto flag must set and twint must be cleared by writing a logic one to it. this causes the twi to enter the not addressed slave mode and to clear the twsto flag (no other bits in twcr are affected). the sda and scl lines are released, and no stop condition is transmitted. s sla r a data a $a8 $b8 a $b0 reception of the own slave address and one or more data bytes last data byte transmitted. switched to not addressed slave (twea = '0') arbitration lost as master and addressed as slave n from master to slave from slave to master any number of data bytes and their associated acknowledge bits this number (contained in twsr) corresponds to a defined state of the two-wire serial bus. the prescaler bits are zero or masked to zero p or s data $c0 data a a $c8 p or s all 1's a
167 2548f?avr?03/2013 atmega406 25.8.6 combining several twi modes in some cases, several twi modes must be combined in order to complete the desired action. consider for example reading data from a serial eeprom. typically, such a transfer involves the following steps: 1. the transfer must be initiated. 2. the eeprom must be instructed what location should be read. 3. the reading must be performed. 4. the transfer must be finished. note that data is transmitted both from master to slave and vice versa. the master must instruct the slave what location it wants to read, requi ring the use of the mt mode. subsequently, data must be read from the slave, implying the use of the mr mode. thus, the transfer direction must be changed. the master must keep control of the bus during all these steps, and the steps should be carried out as an atomic operation. if this principle is violated in a multi-master sys- tem, another master can alter the data pointer in the eeprom between steps 2 and 3, and the master will read the wrong data lo cation. such a change in transfe r direction is accomplished by transmitting a repeated start between the trans mission of the addres s byte and reception of the data. after a repeated start, the mast er keeps ownership of the bus. the following figure shows the flow in this transfer. figure 25-20. combining several twi modes to access a serial eeprom 25.9 multi-master systems and arbitration if multiple masters are connected to the same bus, transmissions may be initiated simultane- ously by one or more of them. the twi standar d ensures that such situations are handled in such a way that one of the mast ers will be allowed to proceed wit h the transfer, and that no data will be lost in the process. an example of an arbitration situat ion is depicted below, where two masters are trying to transmit data to a slave receiver. table 25-7. miscellaneous states status code (twsr) prescaler bits are 0 status of the two-wire serial bus and two-wire serial inter- face hardware application software response next action taken by twi hardware to/from twdr to twcr sta sto twint twea 0xf8 no relevant state information available; twint = ?0? no twdr action no twcr action wait or proceed current transfer 0x00 bus error due to an illegal start or stop condition no twdr action 0 1 1 x only the internal hardware is affected, no stop condi- tion is sent on the bus. in all cases, the bus is released and twsto is cleared. master transmitter master receiver s = start rs = repeated start p = stop transmitted from master to slave transmitted from slave to master s sla+w a address a rs sla+r a data a p
168 2548f?avr?03/2013 atmega406 figure 25-21. an arbitration example several different scenarios may arise du ring arbitration, as described below: ? two or more masters are performing identica l communication with the same slave. in this case, neither the slave nor any of the masters will know about the bus contention. ? two or more masters are accessing the same slave with different data or direction bit. in this case, arbitration will occur, either in the read/wri te bit or in the data bits. the masters trying to output a one on sda while another master outputs a zero will lose the arbitration. losing masters will switch to not addressed slave mode or wait until t he bus is free and transmit a new start condition, depending on application software action. ? two or more masters ar e accessing different slaves. in this case, arbitratio n will occur in the sla bits. masters trying to output a one on sd a while another master outputs a zero will lose the arbitration. masters losing arbitration in sla will switch to slave mode to check if they are being addressed by the winning master. if addressed, they will switch to sr or st mode, depending on the value of the read/write bit. if they are not being addr essed, they will switch to not addressed slave mode or wait until the bus is free and transmit a new start condition, depending on ap plication software action. this is summarized in figure 25-22 . possible status values are given in circles. figure 25-22. possible status codes caused by arbitration device 1 master transmitter device 2 master transmitter device 3 slave receiver device n sda scl ........ r1 r2 v bus own address / general call received arbitration lost in sla twi bus will be released and not addressed slave mode will be entered a start condition will be transmitted when the bus becomes free no arbitration lost in data direction ye s write data byte will be received and not ack will be returned data byte will be received and ack will be returned last data byte will be transmitted and not ack should be received data byte will be transmitted and ack should be received read b0 68/78 38 sla start data stop
169 2548f?avr?03/2013 atmega406 25.10 bus connect/disconnect for two-wire serial interface the bus connect/disconnect module is an addition to the twi interface. based on a configura- tion bit, an interrupt can be generated either wh en the twi bus is connected or disconnected. figure 25-23 illustrates the bus connect/disconnect logic, where sda and scl are the twi data and clock lines, respectively. when the twi bus is connected, both the sda and the scl lines will be come high simultane- ously. if the twbcip bit is cleared, the interru pt will be executed if enabled. once the bus is connected, the twbcip bit should be set. this enables detection of w hen the bus is discon- nected, and prevents repetitive interrupts every time both the sda and scl lines are high (e.g. bus idle state). when the twi bus is disconne cted, both the sda and the sc l lines will become low simultane- ously. if the twbcip bit is set, the interrupt will be executed if enabled and if both lines remain low for a configurable time period. by adding this time constraint, unwanted interrupts caused by both lines going low during normal bus communication is prevented. figure 25-23. overview of bus connect/disconnect. 25.10.1 twbcsr ? twi bus control and status register ? bit 7 - twbcif: twi bus connect/disconnect interrupt flag based on the twbcip bit, the twbcif bit is set when the twi bus is connected or discon- nected. twbcif is cleared by hardware when ex ecuting the corresponding interrupt handling vector. alternatively, twbcif is cleared by writ ing a logic one to the flag. when the sreg i-bit, twbcie (twi bus connect/disconnect interrup t enable), and twbcif are set, the twi bus delay element start output delay twbcsr s da s cl set twbcif ir q twbdt twbcip 8-bit data bus bit 7 6 5 4 3 2 1 0 (0xbe) twbcif twbcie ? ? ? twbdt1 twbdt0 twbcip twbcsr read/write r/w r/w r r r r/w r/w r/w initial value x 00000 0 0
170 2548f?avr?03/2013 atmega406 connect/disconnect interrupt is executed. if bo th sda and scl are high during reset, twbcif will be set after reset. otherwise twbcif will be cleared after reset. ? bit 6 - twbcie: twi bus connect/disconnect interrupt enable when the twbcie bit and the i-bit in the status register are set, the twi bus connect/discon- nect interrupt is enabled. the corresponding interrupt is executed if a twi bus connect/disconnect occurs, i.e., when the twbcie bit is set. ? bit 5:3 - res: reserved bits these bits are reserved bits in the atmega406 and will always read as zero. ? bit 2:1 - twbdt1, twbdt0: twi bus disconnect time-out period the twbdt bits decides how long both the twi data (sda) and clock (scl) signals must be low before generating the twi bus disconnect inte rrupt. the different co nfiguration values and their corresponding time-out periods are shown in table 25-8 . ? bit 0 - twbcip: twi bus connect/disconnect interrupt polarity the twbcip bit decide if the twi bus connec t/disconnect interrupt flag (twbcif) should be set on a bus connect or a bus disconnect. if twbcip is cleared, the twbcif flag is set on a bus connect. if twbcip is set, the tw bcif flag is set on a bus disconnect. table 25-8. tw bus disconnect time-out period twbdt1 twbdt0 twi bus disconnect time-out period 0 0 250 ms 0 1 500 ms 1 0 1000 ms 1 1 2000 ms
171 2548f?avr?03/2013 atmega406 26. jtag interface and on-chip debug system 26.1 features ? jtag (ieee std. 1149.1 compliant) interface ? debugger access to: ? all internal peripheral units ? internal and external ram ? the internal register file ?program counter ? eeprom and flash memories ? extensive on-chip debug support for break conditions, including ? avr break instruction ? break on change of program memory flow ? single step break ? program memory break points on single address or address range ? data memory break points on single address or address range ? programming of flash, eeprom , fuses, and lock bits th rough the jtag interface ? on-chip debugging supported by avr studio ? 26.2 overview the avr ieee std. 1149.1 compliant jtag interface can be used for ? programming the non-volatile memories, fuses and lock bits ? on-chip debugging a brief description is given in the following se ctions. detailed descriptions for programming via the jtag interface can be found in the section ?programming via the jtag interface? on page 211 . the on-chip debug support is considered bei ng private jtag instructions, and distributed within atmel and to selected third party vendors only. figure 26-1 shows a block diagram of the jtag interface and the on-chip debug system. the tap controller is a state machine controlled by the tck and tms signals. the tap controller selects either the jtag instruction register or one of several data registers as the scan chain (shift register) between the tdi ? input and tdo ? output. the instruction register holds jtag instructions controlling the be havior of a data register. the jtag programming interface (actually consis ting of several physical and virtual data reg- isters) is used for serial programming via the jtag interface. the internal scan chain and break point scan chain are used for on-chip debugging only. 26.3 test access port ? tap the jtag interface is accessed through four of the avr?s pins. in jtag terminology, these pins constitute the test access port ? tap. these pins are: ? tms: test mode select. this pin is used for navigating through the tap-controller state machine. ? tck: test clock. jtag operation is synchronous to tck. ? tdi: test data in. serial input da ta to be shifted in to the instruction register or data register (scan chains). ? tdo: test data out. serial output data fr om instruction register or data register.
172 2548f?avr?03/2013 atmega406 the ieee std. 1149.1 also specif ies an optional tap signal; trst ? test reset ? which is not provided. when the jtagen fuse is unprogrammed, these four tap pins are normal port pins, and the tap controller is in reset. when programmed, t he input tap signals are internally pulled high and the jtag is enabled for programming. the device is shipped with this fuse programmed. for the on-chip debug system, in addition to the jtag interface pins, the reset pin is moni- tored by the debugger to be able to detect ex ternal reset sources. the debugger can also pull the reset pin low to reset the whole system, assumi ng only open collectors on the reset line are used in the application. figure 26-1. block diagram tap controller tdi tdo tck tms flash memory avr cpu digital peripheral units jtag / avr core communication interface breakpoint unit flow control unit ocd status and control internal scan chain m u x instruction register id register bypass register jtag programming interface pc instruction address data breakpoint scan chain address decoder
173 2548f?avr?03/2013 atmega406 figure 26-2. tap controller state diagram 26.4 tap controller the tap controller is a 16-state finite state mach ine that controls the operation of the jtag pro- gramming circuitry, or on-chip debug syst em. the state transitions depicted in figure 26-2 depend on the signal present on tms (shown adjacent to each state transition) at the time of the rising edge at tck. the initial state after a power-on reset is test-logic-reset. as a definition in this document, the lsb is shifted in and out first for all shift registers. assuming run-test/idle is the present state, a ty pical scenario for using the jtag interface is: ? at the tms input, apply the sequence 1, 1, 0, 0 at the rising edges of tck to enter the shift instruction register ? sh ift-ir state. while in this state, shift the four bits of the jtag instructions into the jt ag instruction register from the tdi input at the rising edge of tck. the tms input must be held low during input of the 3 lsbs in order to remain in the shift-ir state. the msb of the instruction is shifted in w hen this state is left by setting tms high. while the instruction is shifted in from the tdi pin, the captured ir-state 0x01 is shifted out on the tdo pin. the jtag instruction selects a partic ular data register as path between tdi and tdo and controls the circuitry surr ounding the selected data register. test-logic-reset run-test/idle shift-dr exit1-dr pause-dr exit2-dr update-dr select-ir scan capture-ir shift-ir exit1-ir pause-ir exit2-ir update-ir select-dr scan capture-dr 0 1 0 11 1 00 00 11 1 0 1 1 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1
174 2548f?avr?03/2013 atmega406 ? apply the tms sequence 1, 1, 0 to re-enter th e run-test/idle state. the instruction is latched onto the parallel output from the shift register path in the update-ir st ate. the exit-ir, pause- ir, and exit2-ir states are only us ed for navigating the state machine. ? at the tms input, apply the sequence 1, 0, 0 at the rising edges of tck to enter the shift data register ? shift-dr state. while in this state, upload the selected data r egister (selected by the present jtag instruction in the jtag instruction register) from the tdi input at the rising edge of tck. in order to remain in the shift-dr state, the tms input must be held low during input of all bits except the msb. the msb of the data is shifted in when this state is left by setting tms high. while the data register is shifted in from the tdi pin, the parallel inputs to the data register captured in the capture-dr state is shifted out on the tdo pin. ? apply the tms sequence 1, 1, 0 to re-enter the run-test/idle state. if the selected data register has a latched parallel-output, the latching take s place in the update- dr state. the exit-dr, pause-dr, and exit2-dr states are only used for navigating the state machine. as shown in the state diagram, the run-tes t/idle state need not be entered between selecting jtag instruction and using data registers, and so me jtag instructions may select certain func- tions to be performed in the run-test/idle, making it unsuitable as an idle state. note: independent of the initial state of the tap c ontroller, the test-logic-reset state can always be entered by holding tms high for five tck clock periods. for detailed information on the jtag specific ation, refer to the literature listed in ?jtag inter- face and on-chip debug system? on page 171 . 26.5 using the on-c hip debug system as shown in figure 26-1 , the hardware support for on-chip debugging consists mainly of ? a scan chain on the interface between the internal avr cpu and the internal peripheral units. ? break point unit. ? communication interface between the cpu and jtag system. all read or modify/write operations needed for implementing the debugger are done by applying avr instructions via the internal avr cpu scan chain. the cpu sends the result to an i/o memory mapped location which is part of the communication interface between the cpu and the jtag system. the break point unit implements break on change of program flow, single step break, two program memory break points, and two combined break points. together, the four break points can be configured as either: ? 4 single program memory break points. ? 3 single program memory break point + 1 single data memory break point. ? 2 single program memory break points + 2 single data memory break points. ? 2 single program memory break points + 1 program memory break point with mask (?range break point?). ? 2 single program memory break points + 1 data memory break point with mask (?range break point?). a debugger, like the avr studio, may however use one or more of these resources for its inter- nal purpose, leaving less flexibility to the end-user. a list of the on-chip debug specific jtag instructions is given in ?on-chip debug specific jtag instructions? on page 175 .
175 2548f?avr?03/2013 atmega406 the jtagen fuse must be programmed to enable the jtag test access port. in addition, the ocden fuse must be programmed and no lock bits must be set for the on-chip debug system to work. as a security feature, the on-chip debug system is disabled when either of the lb1 or lb2 lock bits are set. otherwise, the on-chi p debug system would have provided a back-door into a secu red device. the avr studio enables the user to fully contro l execution of programs on an avr device with on-chip debug capability, avr in- circuit emulator, or the built-i n avr instruction set simulator. avr studio ? supports source level execution of assembly programs assembled with atmel cor- poration?s avr assembler and c programs compiled with third party vendors? compilers. avr studio runs under microsoft ? windows ? 95/98/2000 and microsoft windows nt ? . for a full description of the avr studio, please re fer to the avr studio user guide. only high- lights are presented in this document. all necessary execution commands are available in avr studio, both on source level and on disassembly level. the user can execute the program, single step through the code either by tracing into or stepping over functions, step ou t of functions, place the cursor on a statement and execute until the st atement is reached, stop the executio n, and reset the execution target. in addition, the user can have an unlimited number of code break points (using the break instruction) and up to two data memory break points, alternatively combined as a mask (range) break point. 26.6 on-chip debug specific jtag instructions the on-chip debug support is considered being pr ivate jtag instructions, and distributed within atmel and to selected third pa rty vendors only. instruction opcodes are listed for reference. 26.6.1 private0; 0x8 private jtag instruction for accessing on-chip debug system. 26.6.2 private1; 0x9 private jtag instruction for accessing on-chip debug system. 26.6.3 private2; 0xa private jtag instruction for accessing on-chip debug system. 26.6.4 private3; 0xb private jtag instruction for accessing on-chip debug system.
176 2548f?avr?03/2013 atmega406 26.7 on-chip debug related register 26.7.1 ocdr ? on-chi p debug register the ocdr register provides a co mmunication channel from the running pr ogram in the micro- controller to the debugger. the cpu can transfer a byte to the debugger by writing to this location. at the same time, an in ternal flag; i/o debug register dirty ? idrd ? is set to indicate to the debugger that the register has been writ ten. when the cpu reads the ocdr register the 7 lsb will be from the ocdr regi ster, while the msb is the idrd bit. the debugger clears the idrd bit when it has read the information. in some avr devices, this register is shared wi th a standard i/o location. in this case, the ocdr register can only be accessed if the ocden fuse is programmed, and the debugger enables access to the ocdr register. in all other case s, the standard i/o location is accessed. refer to the debugger documentation for furt her information on how to use this register. 26.7.2 mcucr ? mcu control register the mcu control register contains co ntrol bits for general mcu functions. ? bit 7 - jtd: jtag interface disable when this bit is zero, the jtag interface is ena bled if the jtagen fuse is programmed. if this bit is one, the jtag interface is disabled. in order to avoid unintentional disabling or enabling of the jtag interface, a timed sequence must be followed when changing this bit: the application software must write this bit to the desired value twice within fo ur cycles to change its value. note that this bit must not be alte red when using the on-chip debug system. bit 7 6543210 0x31 (0x51) on-chip debug register ocdr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0000000 bit 7 6543210 0x35 (0x55) jtd pud ivsel ivce mcucr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0000000
177 2548f?avr?03/2013 atmega406 26.8 using the jtag programming capabilities programming of avr parts via jtag is performed via the 4-pin jtag port, tck, tms, tdi, and tdo. these are the only pins that need to be controlled/observed to perform jtag program- ming (in addition to power pins). it is not requi red to apply 12v externally. the jtagen fuse must be programmed and the jtd bit in the mc ucr register must be cleared to enable the jtag test access port. the jtag programmi ng capability supports: ? flash programming and verifying. ? eeprom programming and verifying. ? fuse programming and verifying. ? lock bit programming and verifying. the lock bit security is exactly as in parallel programming mode. if the lock bits lb1 or lb2 are programmed, the ocden fuse cannot be programmed unless first doing a chip erase. this is a security feature that ensures no back-door exists for reading out the content of a secured device. the details on programming through the jtag interface and programming specific jtag instructions are given in the section ?programming via the jtag interface? on page 211 .
178 2548f?avr?03/2013 atmega406 27. boot loader supp ort ? read-while-wri te self-programming the boot loader support provides a real read- while-write self-programming mechanism for downloading and uploading program code by the m cu itself. this feature a llows flexible applica- tion software updates controlled by the mcu us ing a flash-resident boot loader program. the boot loader program can use any available data interface and associated protocol to read code and write (program) that code into the flash memory, or read the code from the program mem- ory. the program code within the boot loader sect ion has the capability to write into the entire flash, including the boot loader memory. the boot loader can t hus even modify itself, and it can also erase itself from the code if the feature is not needed anymore. the size of the boot loader memory is configurable with fuses and t he boot loader has two separate sets of boot lock bits which can be set indepen dently. this gives the user a uniq ue flexibility to select differ- ent levels of protection. 27.1 boot loader features ? read-while-write self-programming ? flexible boot memory size ? high security (separate boot lock bits for a flexible protection) ? separate fuse to select reset vector ? optimized page (1) size ? code efficient algorithm ? efficient read-modi fy-write support note: 1. a page is a section in the flas h consisting of several bytes (see ?page size? on page 198 ) used during programming. the page organization does not affect normal operation. 27.2 application and boot loader flash sections the flash memory is organized in two main sections, the application section and the boot loader section (see figure 27-2 ). the size of the different se ctions is configured by the bootsz fuses as shown in table 27-7 on page 193 and figure 27-2 . these two sections can have different level of protection since they have different sets of lock bits. 27.2.1 application section the application section is the section of the flas h that is used for storing the application code. the protection level for the application section can be selected by the application boot lock bits (boot lock bits 0), see table 27-2 on page 182 . the application section can never store any boot loader code since the spm instruction is disabled when executed from the application section. 27.2.2 bls ? boot loader section while the application section is used for storing the application code, the the boot loader soft- ware must be located in the bls since the spm instruction can initiate a programming when executing from the bls only. the spm instruct ion can access the entir e flash, including the bls itself. the protection level for the boot loader section can be selected by the boot loader lock bits (boot lock bits 1), see table 27-3 on page 182 .
179 2548f?avr?03/2013 atmega406 27.3 read-while-write and no r ead-while-write flash sections whether the cpu supports read-while-write or if the cpu is halted during a boot loader soft- ware update is dependent on which address that is being programmed. in addition to the two sections that are configurable by the bootsz fuses as described above, the flash is also divided into two fixed sections, the read-whi le-write (rww) secti on and the no read-while- write (nrww) section. the limit between the rww- and nrww sections is given in table 27- 8 on page 193 and figure 27-2 on page 181 . the main difference between the two sections is: ? when erasing or writing a page located insi de the rww section, the nrww section can be read during the operation. ? when erasing or writing a page located inside th e nrww section, the cpu is halted during the entire operation. note that the user software can never read any code that is located insi de the rww section dur- ing a boot loader software operation. the syntax ?read-while-write sect ion? refers to which section that is being programmed (erased or writ ten), not which section that actually is being read during a boot loader software update. 27.3.1 rww ? read-while-write section if a boot loader software update is programmin g a page inside the rww section, it is possible to read code from the flash, but only code that is located in the nrww section. during an on- going programming, the software must ensure that the rww section never is being read. if the user software is trying to read code that is located inside the rww section (i.e., by a call/jmp/lpm or an interrupt) during programming, the software might end up in an unknown state. to avoid this, the interrupts should either be disabled or moved to the boot loader sec- tion. the boot loader section is always loca ted in the nrww section. the rww section busy bit (rwwsb) in the store program memory cont rol and status register (spmcsr) will be read as logical one as long as the rww section is blocked for reading. after a programming is com- pleted, the rwwsb must be cleared by software before reading code located in the rww section. see section ?27.5.1? on page 183. for details on how to clear rwwsb. 27.3.2 nrww ? no read -while-write section the code located in the nrww section can be re ad when the boot loader software is updating a page in the rww section. when the boot l oader code updates the nrww section, the cpu is halted during the entire page erase or page write operation. table 27-1. read-while-write features which section does the z-pointer address during the programming? which section can be read during pr ogramming? cpu halted? read-while-write supported? rww section nrww section no yes nrww section none yes no
180 2548f?avr?03/2013 atmega406 figure 27-1. read-while-write vs. no read-while-write read-while-write (rww) section no read-while-write (nrww) section z-pointer addresses rww section z-pointer addresses nrww section cpu is halted during the operation code located in nrww section can be read during the operation
181 2548f?avr?03/2013 atmega406 figure 27-2. memory sections note: 1. the parameters in the figure above are given in table 27-7 on page 193 . 27.4 boot loader lock bits if no boot loader capability is n eeded, the entire flash is available for application code. the boot loader has two separate sets of boot lock bits which can be set independently. this gives the user a unique flexibility to sele ct different levels of protection. the user can select: ? to protect the entire flash from a software update by the mcu. ? to protect only the boot loader flash sect ion from a software update by the mcu. ? to protect only the application flash se ction from a software update by the mcu. ? allow software update in the entire flash. see table 27-2 and table 27-3 for further details. th e boot lock bits can be set in software and in serial or parallel programming mode, but they can be cleared by a chip erase command only. the general write lock (lock bit mode 2) does not control the programming of the flash memory by spm instruction. sim ilarly, the general read/write lock (lock bit mode 1) does not control reading nor writing by lpm/spm, if it is attempted. 0x0000 flashend program memory bootsz = '11' application flash section boot loader flash section flashend program memory bootsz = '10' 0x0000 program memory bootsz = '01' program memory bootsz = '00' application flash section boot loader flash section 0x0000 flashend application flash section flashend end rww start nrww application flash section boot loader flash section boot loader flash section end rww start nrww end rww start nrww 0x0000 end rww, end application start nrww, start boot loader application flash section application flash section application flash section read-while-write section no read-while-write section read-while-write section no read-while-write section read-while-write section no read-while-write section read-while-write section no read-while-write section end application start boot loader end application start boot loader end application start boot loader
182 2548f?avr?03/2013 atmega406 note: 1. ?1? means unprogrammed, ?0? means programmed note: 1. ?1? means unprogrammed, ?0? means programmed table 27-2. boot lock bit0 protection modes (application section) (1) blb0 mode blb02 blb01 protection 111 no restrictions for spm or lpm accessing the application section. 2 1 0 spm is not allowed to write to the application section. 300 spm is not allowed to write to the application section, and lpm executing from the boot loader se ction is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrup ts are disabled while executing from the application section. 401 lpm executing from the boot loa der section is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. table 27-3. boot lock bit1 protection modes (boot loader section) (1) blb1 mode blb12 blb11 protection 111 no restrictions for spm or lpm accessing the boot loader section. 2 1 0 spm is not allowed to write to the boot loader section. 300 spm is not allowed to write to th e boot loader section, and lpm executing from the application section is not allowed to read from the boot loader section. if interrupt vectors are placed in the application section, interrupts are disabled while executing from the boot loader section. 401 lpm executing from the applicat ion section is not allowed to read from the boot loader section. if interrupt vectors are placed in the application section, interrupts are disabled while executing from the boot loader section.
183 2548f?avr?03/2013 atmega406 27.5 entering the boot loader program entering the boot loader takes place by a jump or call from the application program. this may be initiated by a trigger such as a command received via the twi interface. alternatively, the boot reset fuse can be programmed so that the re set vector is pointing to the boot flash start address after a reset. in this case, the boot lo ader is started after a reset. after the application code is loaded, the program can start executing the application code. note that the fuses cannot be changed by the mcu itself. this means that once the boot reset fuse is programmed, the reset vector will always point to the boot loader reset and th e fuse can only be changed through the serial or parallel programming interface. note: 1. ?1? means unprogrammed, ?0? means programmed 27.5.1 spmcsr ? store program memory control and status register the store program memory control and status regi ster contains the control bits needed to con- trol the boot loader operations. ? bit 7 ? spmie: spm interrupt enable when the spmie bit is written to one, and the i-bi t in the status register is set (one), the spm ready interrupt will be enabled. the spm ready in terrupt will be ex ecuted as long as the spmen bit in the spmcsr register is cleared. ? bit 6 ? rwwsb: read-while-write section busy when a self-programming (page erase or page write) operation to the rww section is initi- ated, the rwwsb will be set (one ) by hardware. when the rwwsb bit is set, the rww section cannot be accessed. the rwwsb bit will be cleared if the rwwsre bit is written to one after a self-programming operation is completed. alter natively the rwwsb bit will automatically be cleared if a page load operation is initiated. ? bit 5 - sigrd: signature row read if this bit is written to one at the same time as spmen, the next lpm instruction within three clock cycles will read a byte from the signature row into the destinatio n register. see ?reading the signature row from software? on page 189 for details. an spm instruction within four cycles after sigrd and spmen are set will have no effect. this operation is reserved for future use and should not be used. table 27-4. boot reset fuse (1) bootrst reset address 1 reset vector = application reset (address 0x0000) 0 reset vector = boot loader reset (see table 27-7 on page 193 ) bit 7 6 5 4 3 2 1 0 0x37 (0x57) spmie rwwsb sigrd rwwsre blbset pgwrt pgers spmen spmcsr read/write r/w r r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
184 2548f?avr?03/2013 atmega406 ? bit 4 ? rwwsre: read-while-write section read enable when programming (page erase or page write) to the rww section, the rww section is blocked for reading (the rwwsb will be set by ha rdware). to re-enable the rww section, the user software must wait until the programming is complet ed (spmen will be cl eared). then, if the rwwsre bit is written to one at the same time as spmen, the next spm instruction within four clock cycles re-enables the rww secti on. the rww section cannot be re-enabled while the flash is busy with a page erase or a page wr ite (spmen is set). if the rwwsre bit is writ- ten while the flash is being loaded, the flash load operation will abort and the data loaded will be lost. ? bit 3 ? blbset: boot lock bit set if this bit is written to one at the same time as spmen, the next spm inst ruction within four clock cycles sets boot lock bits, according to the data in r0. the data in r1 and the address in the z- pointer are ignored. the blbset bit will autom atically be cleared upon completion of the lock bit set, or if no spm instruction is executed within four clock cycles. an lpm instruction within three cycles after blbset and spmen are set in the spmcsr reg- ister, will read either the lock bits or the fuse bits (depending on z0 in the z-pointer) into the destination register. see ?reading the fuse and lock bits from software? on page 188 for details. ? bit 2 ? pgwrt: page write if this bit is written to one at the same time as spmen, the next spm inst ruction within four clock cycles executes page write, with the data stored in the temporary buffer. the page address is taken from the high part of the z-pointer. the data in r1 and r0 are ignored. the pgwrt bit will auto-clear upon co mpletion of a page write, or if no spm instruction is ex ecuted within four clock cycles. the cpu is halted during the ent ire page write operation if the nrww section is addressed. ? bit 1 ? pgers: page erase if this bit is written to one at the same time as spmen, the next spm inst ruction within four clock cycles executes page erase. the page address is taken from the high part of the z-pointer. the data in r1 and r0 are ignored. the pgers bi t will auto-clear upon comp letion of a page erase, or if no spm instruction is executed within four clock cycles. the cpu is halted during the entire page write operation if the nrww section is addressed. ? bit 0 ? spmen: store program memory enable this bit enables the spm instruction for the next fo ur clock cycles. if written to one together with either rwwsre, blbset, pgwrt? or pgers, t he following spm instruction will have a spe- cial meaning, see description abo ve. if only spmen is written, the following spm instruction will store the value in r1:r0 in the temporary page buffer addressed by the z-pointer. the lsb of the z-pointer is ignored. the spmen bit will aut o-clear upon completion of an spm instruction, or if no spm instruction is executed within fo ur clock cycles. during page erase and page write, the spmen bit remains high until the operation is completed. writing any other combination than ?100001?, ?010001?, ?001001?, ?000101?, ?000011? or ?000001? in the lower five bits will have no effect.
185 2548f?avr?03/2013 atmega406 27.6 addressing the flash during self-programming the z-pointer is used to address the spm commands. since the flash is organized in pages (see ?fuse bits? on page 196 ), the program counter can be treated as having two different sections. one sect ion, consisting of the least significant bits, is addressing the words within a page, while the most significant bits are addressing the pages. this is shown in figure 27-3 . note that the page erase and page write operations are addressed independently. therefor e it is of major importance that the boot loader software addresses the same page in both the page eras e and page write operation. once a program- ming operation is initiated, the address is latched and the z-pointer can be used for other operations. the only spm operation that does not use the z-pointer is setting the boot loader lock bits. the content of the z-pointer is ignored and will have no effect on the operation. the lpm instruction does also use the z-pointer to store the address. since this instruction addresses the flash byte-by-byte, also the lsb (bit z0) of the z-pointer is used. figure 27-3. addressing the flash during spm (1) note: 1. the different variables used in figure 27-3 are listed in table 27-9 on page 193 . bit 151413121110 9 8 zh (r31) z15 z14 z13 z12 z11 z10 z9 z8 zl (r30) z7z6z5z4z3z2z1z0 76543210 program memory 0 1 15 z - register bit 0 zpagemsb word address within a page page address within the flash zpcmsb instruction word pag e pcword[pagemsb:0]: 00 01 02 pageend pag e pcword pcpage pcmsb pagemsb program counter
186 2548f?avr?03/2013 atmega406 27.7 self-programming the flash the program memory is updated in a page by page fashion. before programming a page with the data stored in the temporary page buffer, the page must be erased. the temporary page buf- fer is filled one word at a time using spm and the buffer can be filled either before the page erase command or between a page erase and a page write operation: alternative 1, fill the bu ffer before a page erase ? fill temporary page buffer ? perform a page erase ? perform a page write alternative 2, fill the bu ffer after page erase ? perform a page erase ? fill temporary page buffer ? perform a page write if only a part of the page needs to be changed, th e rest of the page must be stored (for example in the temporary page buffer) before the erase, and then be rewritten. w hen using alternative 1, the boot loader provides an effective read-mod ify-write feature which a llows the user software to first read the page, do the necessary changes, and then write back the modified data. if alter- native 2 is used, it is not possible to read the old data while loading since the page is already erased. the temporary page buffer can be accessed in a random sequence. it is essential that the page address used in both the page erase and page write operation is addressing the same page. see ?simple assembly code example for a boot loader? on page 191 for an assembly code example. 27.7.1 performing page erase by spm to execute page erase, set up the address in the z-pointer, write ?x0000011? to spmcsr and execute spm within four clock cycl es after writing spmcsr. the data in r1 and r0 is ignored. the page address must be written to pcpage in the z-register. other bits in the z-pointer will be ignored during this operation. ? page erase to the rww section: the nrww section can be read during the page erase. ? page erase to the nrww section: the cpu is halted during the operation. 27.7.2 filling the temporary buffer (page loading) to write an instruction word, set up the addres s in the z-pointer and data in r1:r0, write ?00000001? to spmcsr and execute spm within four clock cycles after writing spmcsr. the content of pcword in the z-register is used to address the data in the temporary buffer. the temporary buffer will auto-erase after a page write operation or by writing the rwwsre bit in spmcsr. it is also erased after a system reset. no te that it is not possible to write more than one time to each address without erasing the temporary buffer.
187 2548f?avr?03/2013 atmega406 27.7.3 performing a page write to execute page write, set up the address in the z-pointer, write ?x0000101? to spmcsr and execute spm within four clock cycl es after writing spmcsr. the data in r1 and r0 is ignored. the page address must be writte n to pcpage. other bits in th e z-pointer will be ignored during this operation. ? page write to the rww section: the nrww section can be read during the page write. ? page write to the nrww section: the cpu is halted during the operation. 27.7.4 using the spm interrupt if the spm interrupt is en abled, the spm interrupt will genera te a constant interrupt when the spmen bit in spmcsr is cleared. this means th at the interrupt can be used instead of polling the spmcsr register in softwar e. when using the spm interrupt, the interrupt vectors should be moved to the bls section to avoid that an in terrupt is accessing the rww section when it is blocked for reading. how to move the interrupts is described in ?interrupts? on page 51 . 27.7.5 consideration while updating bls special care must be taken if the user allows the boot loader section to be updated by leaving boot lock bit11 unprogrammed. an accidental writ e to the boot loader itself can corrupt the entire boot loader, and further software updates might be impossible. if it is not necessary to change the boot loader software itself, it is recommended to program the boot lock bit11 to protect the boot loader software from any internal software changes. 27.7.6 prevent reading the rww section during self-programming during self-programming (either page erase or page write), the rww section is always blocked for reading. the user software itself must prevent that this section is addressed during the self programming operation. the rwwsb in the spmcsr will be set as long as the rww section is busy. during self-programming the inte rrupt vector table should be moved to the bls as described in ?interrupts? on page 51 , or the interrupts must be disabled. before addressing the rww section after the programming is completed, the user software must clear the rwwsb by writing the rwwsre. see ?simple assembly code example for a boot loader? on page 191 for an example. 27.7.7 setting the boot loader lock bits by spm to set the boot loader lock bits, write the desired data to r0, write ?x0001001? to spmcsr and execute spm within four cloc k cycles after writing spmcsr. the only accessible lock bits are the boot lock bits that ma y prevent the application and boot loader section from any soft- ware update by the mcu. see table 27-2 and table 27-3 for how the different settings of the boot loader bits affect the flash access. if bits 5:2 in r0 are cleared (zero), the corre sponding boot lock bit will be programmed if an spm instruction is executed within four cycles after blbset and spmen are set in spmcsr. the z-pointer is don?t ca re during this operation, but for fu ture compatibility it is recommended to load the z-pointer with 0x0001 (same as used for reading the lo ck bits). for future compatibility it bit 76543210 r0 1 1 blb12 blb11 blb02 blb01 1 1
188 2548f?avr?03/2013 atmega406 is also recommended to set bits 7, 6, 1, and 0 in r0 to ?1? when writing the lock bits. when pro- gramming the lock bits the entire flash can be read during the operation. 27.7.8 eeprom write prevents writing to spmcsr note that an eeprom write oper ation will block all software progra mming to flash. reading the fuses and lock bits from software will also be prevented during t he eeprom write operation. it is recommended that the user checks the status bit (eewe) in the eecr register and verifies that the bit is cleared before writing to the spmcsr register. 27.7.9 reading the fuse and lock bits from software it is possible to read both the fuse and lock bi ts from software. to read the lock bits, load the z-pointer with 0x0001 and set the blbset and spmen bits in spmcsr. when an lpm instruc- tion is executed within three cpu cycles after the blbset and spmen bits are set in spmcsr, the value of the lock bits will be loaded in the destination register. the blbset and spmen bits will auto-clear upon completion of reading the lo ck bits or if no lpm instruction is executed within three cpu cycles or no spm instruction is executed within four cpu cycles. when blb- set and spmen are cleared, lpm will work as described in the ? avr instruction set? description. the algorithm for reading the fuse low byte is similar to the one described above for reading the lock bits. to read the fuse low byte, load the z-pointer with 0x0000 and set the blbset and spmen bits in spmcsr. when an lpm instruct ion is executed within three cycles after the blbset and spmen bits are set in the spmcsr, the value of the fuse low byte (flb) will be loaded in the destination regist er as shown below. refer to table 28-4 on page 197 for a detailed description and mapping of the fuse low byte. similarly, when reading the fuse high byte, load 0x0003 in the z-pointer. when an lpm instruc- tion is executed within three cycles after the blbset and spmen bits are set in the spmcsr, the value of the fuse high byte (fhb) will be load ed in the destination re gister as shown below. refer to table 28-3 on page 196 for detailed description and mapping of the fuse high byte. fuse and lock bits that are programmed, will be read as zero. fuse and lock bits that are unprogrammed, will be read as one. bit 76543210 rd ? ? blb12 blb11 blb02 blb01 lb2 lb1 bit 76543210 rd flb7 flb6 flb5 flb4 flb3 flb2 flb1 flb0 bit 76543210 rd fhb7 fhb6 fhb5 fhb4 fhb3 fhb2 fhb1 fhb0
189 2548f?avr?03/2013 atmega406 27.7.10 reading the signa ture row from software to read the signature row from software, load the z-pointer with the signature byte address given in table 27-5 and set the sigrd and spmen bits in spmcsr. when an lpm instruction is executed within three cpu cycles after t he sigrd and spmen bits are set in spmcsr, the signature byte value will be loaded in the desti nation register. the sigrd and spmen bits will auto-clear upon completion of reading the signature row lock bits or if no lpm instruction is executed within three cpu cycles. when s igrd and spmen are cleared, lpm will work as described in the ?avr instruction set? description. table 27-5. signature row addressing signature byte z-pointer address device id 0, manufacture id 0x00 device id 1, flash size 0x02 device id 2, device 0x04 fosccal (1) 0x01 reserved 0x03 slow rc frq (2) 0x05 slow rc l 0x06 slow rc h (3) 0x07 slow rc temp prediction l 0x0c slow rc temp prediction h (7) 0x0d ulp rc frq (5) 0x08 ulp rc l 0x0a ulp rc h (6) 0x0b bandgap ptat current calibration byte (4) 0x09 v-adc raw cell 1 l 0x0e v-adc raw cell 1 h (8) 0x0f v-adc cell1 gain calibration word l 0x10 v-adc cell1 gain calibration word h (9) 0x11 v-adc cell2 gain calibration word l 0x12 v-adc cell2 gain calibration word h (9) 0x13 v-adc cell3 gain calibration word l 0x14 v-adc cell3 gain calibration word h (9) 0x15 v-adc cell4 gain calibration word l 0x16 v-adc cell4 gain calibration word h (9) 0x17 v-adc adc0 gain calibration word l 0x18 v-adc adc0 gain calibration word h (10) 0x19 v-adc cell1 offset (12) 0x1c
190 2548f?avr?03/2013 atmega406 notes: 1. default foscca l value after reset. 2. slow rc oscillator frequency in khz 3. slow rc oscillator fastest timeout in s. 4. calibration value found for bgccr which gives 1.1v at vref when bgcrr = 0x0f. 5. ulp rc oscillator frequency in khz. 6. ulp rc oscillator fastest timeout in s. 7. slow rc oscillator frequency temperature drif t prediction value (word). measured over sev- eral lots. not implemented. 8. calibration word used for the second step of vr ef calibration. this step is performed by the customer at 25 ? c. value stored is vadch/l w hen cell1 had 4096 mv at 85 ? c. 9. calibration word used to compensate for gain error in v-adc cell input 1 - 4. cell x in mv = vadch/l*this word/16384. 10. calibration word used to compensate for gain error in v-adc adc0. adc0 in 0.1mv = vadch/l*this word/16384. 11. calibration word used to calculate the absolute temperature in kelvin from vtemp conver- sion. temp in k = vadch/l*this word/16384. 12. calibration byte used to compensate for offset in v-adc cells. not implemented. all other addresses are reserved for future use. v-adc cell2 offse (12) t 0x1d v-adc cell3 offse (12) t 0x1e v-adc cell4 offset (12) 0x1f vptat cal l 0x1a vptat cal h (11) 0x1b table 27-5. signature row addressing signature byte z-pointer address
191 2548f?avr?03/2013 atmega406 27.7.11 programming time for flash when using spm the fast rc oscillator is used to time flash accesses. table 27-6 shows the typical program- ming time for flash accesses from the cpu. 27.7.12 simple assembly code example for a boot loader ;-the routine writes one page of data from ram to flash ; the first data location in ram is pointed to by the y pointer ; the first data location in flash is pointed to by the z-pointer ;-error handling is not included ;-the routine must be placed inside the boot space ; (at least the do_spm sub routine). only code inside nrww section ; can be read during self-programming (page erase and page write). ;-registers used: r0, r1, temp1 (r16), temp2 (r17), looplo (r24), ; loophi (r25), spmcrval (r20) ; storing and restoring of registers is not included in the routine ; register usage can be optimized at the expense of code size ;-it is assumed that either the interrupt table is moved to the ; boot loader section or that the interrupts are disabled. .equ pagesizeb = pagesize*2 ;pagesizeb is page size in bytes, not words .org smallbootstart write_page: ; page erase ldi spmcrval, (1< 192 2548f?avr?03/2013 atmega406 ldi spmcrval, (1< 193 2548f?avr?03/2013 atmega406 27.7.13 atmega406 boot loader parameters in table 27-7 through table 27-9 , the parameters used in the description of the self-program- ming are given note: 1. the different bootsz fuse configurations are shown in figure 27-2 note: 1. for details about these two section, see ?nrww ? no read-while-write section? on page 179 and ?rww ? read-while-write section? on page 179 . table 27-7. boot size configuration (1) bootsz1 bootsz0 boot size pages application flash section boot loader flash section end application section boot reset address (start boot loader section) 11 256 words 4 0x0000 - 0x4eff 0x4f00 - 0x4fff 0x4eff 0x4f00 10 512 words 8 0x0000 - 0x4dff 0x4e00 - 0x4fff 0x4dff 0x4e00 01 1024 words 16 0x0000 - 0x4bff 0x4c00 - 0x4fff 0x4bff 0x4c00 00 2048 words 32 0x0000 - 0x47ff 0x4800 - 0x4fff 0x47ff 0x4800 table 27-8. read-while-write limit (1) section pages address read-while-write section (rww) 288 0x0000 - 0x47ff no read-while-write section (nrww) 32 0x4800 - 0x4fff table 27-9. explanation of different variables used in figure 27-3 and the mapping to the z- pointer (1) variable corresponding z-value description pcmsb 14 most significant bit in the program counter. (the program counter is 13 bits pc[12:0]) pagemsb 5 most significant bit which is used to address the words within one page (64 words in a page requires six bits pc [5:0]). zpcmsb z15 bit in z-register that is mapped to pcmsb. because z0 is not used, the zpcmsb equals pcmsb + 1. zpagemsb z6 bit in z-register that is mapped to pcmsb. because z0 is not used, the zpagemsb equals pagemsb + 1. pcpage pc[14:6] z13:z7 program counter page address: page select, for page erase and page write pcword pc[5:0] z6:z1 program counter word add ress: word select, for filling temporary buffer (must be zero during page write operation)
194 2548f?avr?03/2013 atmega406 note: 1. z0: should be zero for all spm commands, byte select for the lpm instruction. see ?addressing the flash during self-programming? on page 185 for details about the use of z-pointer during self-programming.
195 2548f?avr?03/2013 atmega406 28. memory programming 28.1 program and data memory lock bits the atmega406 provides six lock bits which can be left unprogrammed (?1?) or can be pro- grammed (?0?) to obtain the ad ditional features listed in table 28-2 . the lock bits can only be erased to ?1? with the chip erase command. note: 1. ?1? means unprogrammed, ?0? means programmed table 28-1. lock bit byte (1) lock bit byte bit no description default value 7 ? 1 (unprogrammed) 6 ? 1 (unprogrammed) blb12 5 boot lock bit 1 (unprogrammed) blb11 4 boot lock bit 1 (unprogrammed) blb02 3 boot lock bit 1 (unprogrammed) blb01 2 boot lock bit 1 (unprogrammed) lb2 1 lock bit 1 (unprogrammed) lb1 0 lock bit 1 (unprogrammed) table 28-2. lock bit protection modes (1)(2) memory lock bits protection type lb mode lb2 lb1 1 1 1 no memory lock features enabled. 210 further programming of the flash and eeprom is disabled in parallel and serial programming mode. the fuse bits are locked in both serial and parallel programming mode. (1) 300 further programming and verification of the flash and eeprom is disabled in parallel and serial programming mode. the boot lock bits and fuse bits are locked in both serial and parallel programming mode. (1) blb0 mode blb02 blb01 1 1 1 no restrictions for spm or lpm accessing the app lication section. 2 1 0 spm is not allowed to writ e to the application section. 300 spm is not allowed to write to the application section, and lpm executing from the boot loader sect ion is not allowed to read from the application section. if interrup t vectors are placed in the boot loader section, interrupts are disa bled while executing from the application section. 401 lpm executing from the boot loader section is not allowed to read from the application section. if interrupt vectors are placed in the boot loader section, interrupts ar e disabled while executing from the application section.
196 2548f?avr?03/2013 atmega406 notes: 1. program the fuse bits and boot lock bits before programming the lb1 and lb2. 2. ?1? means unprogrammed, ?0? means programmed 28.2 fuse bits the atmega406 has two fuse bytes. table 28-3 - table 28-4 describe briefly the functionality of all the fuses and how they are map ped into the fuse byte s. note that the fuses are read as logi- cal zero, ?0?, if they are programmed. 28.2.1 high byte notes: 1. never ship a product with the ocden fuse programmed regardless of the setting of lock bits and jtagen fuse. a programmed ocden fuse enables some parts of the clock system to be running in all sleep modes. this may increase the power consumption. blb1 mode blb12 blb11 1 1 1 no restrictions for spm or lpm accessing the boot loader section. 2 1 0 spm is not allowed to write to the boot loader section. 300 spm is not allowed to write to the boot loader section, and lpm executing from the application sect ion is not allowed to read from the boot loader section. if inte rrupt vectors are placed in the application section, interrupts are disabled while executing from the boot loader section. 401 lpm executing from the application section is not allowed to read from the boot loader section. if interrupt vectors are placed in the application section, interrupts are disabled while executing from the boot loader section. table 28-2. lock bit protection modes (1)(2) (continued) memory lock bits protection type table 28-3. fuse high byte fuse high byte bit no description default value ?7? 1 ?6? 1 ?5? 1 ?4? 1 ?3? 1 ?2? 1 ocden (1) 1 enable ocd 1 (unprogrammed, ocd disabled) jtagen 0 enable jtag 0 (programmed, jtag enabled)
197 2548f?avr?03/2013 atmega406 28.2.2 low byte notes: 1. the default value of sut1:0 results in maximum start-up time for the default clock source. see table 7-2 on page 28 for details. 2. the default value of bootsz1:0 re sults in maximum boot size. see table 27-7 on page 193 for details. 3. see ?wdtcsr ? watchdog timer control register? on page 47 for details. 4. when unpgrogrammed, internal rc oscillator is used. programming this fuse is for test pur- pose only, and should not be used in application. the status of the fuse bits is not affected by chip erase. note that the fuse bits are locked if lock bit1 (lb1) is programmed. program the fuse bits before programming the lock bits. 28.2.3 latching of fuses the fuse values are latched when the device enters programming mode and changes of the fuse values will have no effect until the part leaves programming mode. this does not apply to the eesave fuse which will take effect once it is programmed. the fuse s are also latched on power-up in normal mode. table 28-4. fuse low byte fuse low byte bit no description default value wdton (3) 7 watchdog timer always on 1 (unprogrammed) eesave 6 eeprom memory is preserved through the chip erase 1 (unprogrammed, eeprom not preserved) bootsz1 5 select boot size (see table 27-7 on page 193 for details) 0 (programmed) (2) bootsz0 4 select boot size (see table 27-7 on page 193 for details) 0 (programmed) (2) bootrst 3 select reset vector 1 (unprogrammed) sut1 2 select start-up time 1 (unprogrammed) (1) sut0 1 select start-up time 0 (programmed) (1) cksel 0 clock selection 1 (unprogrammed) (4)
198 2548f?avr?03/2013 atmega406 28.3 signature bytes all atmel microcontrollers have a three-byte signature code which identifies the device. this code can be read in both serial and parallel mode, also when the device is locked. the three bytes reside in a separate address space. for the atmega406 the signature bytes are: 1. 0x000: 0x1e (indicates manufactured by atmel). 2. 0x001: 0x95 (indicates 40kb flash memory). 3. 0x002: 0x07(indicates atmega406 device when 0x001 is 0x95). 28.4 calibration bytes the atmega406 has calibration bytes for the fast rc oscillator, slow rc oscillator, internal voltage reference, internal temperature reference and each differential cell voltage input. these bytes reside in the high bytes in the signature address space. during reset, the calibration byte for the fast rc oscillator is automatically writte n into the corresponding ca libration register. the other calibration bytes should be handl ed by the application software. see ?reading the signa- ture row from soft ware? on page 189 for details. 28.5 page size table 28-5. no. of words in a page and no. of pages in the flash flash size page size pcword no. of pages pcpage pcmsb 20k words (40k bytes) 64 words pc[5:0] 320 pc[14:6] 14 table 28-6. no. of words in a page and no. of pages in the eeprom eeprom size page size pcword no. of pages pcpage eeamsb 512 bytes 4 bytes eea[1:0] 128 eea[8:2] 8
199 2548f?avr?03/2013 atmega406 28.6 parallel programming this section describes parameters, pin mapping, and commands used to parallel program and verify flash program memory, eeprom data memo ry, memory lock bits, an d fuse bits in the atmega406. pulses are assumed to be at least 250 ns unless otherwise noted. 28.6.1 considerations for efficient programming the loaded command and address are retained in the device during programming. for efficient programming, the following should be considered. ? the command needs only be loaded once when writing or reading multiple memory locations. ? skip writing the data value 0xff, that is the contents of the entire eeprom (unless the eesave fuse is programmed) a nd flash after a chip erase. address high byte needs only be loaded before programming or reading a new 256 word win- dow in flash or 256 byte eeprom . this consideration also applie s to signature bytes reading. 28.6.2 signal names in this section, some pins of the atmega406 are referenced by signal names describing their functionality during parallel programming, see figure 28-1 on page 199 and table 28-7 on page 200 . pins not described in the following table are referenced by pin names. the xa1/xa0 pins determine the action executed when the xtal1 pin is given a positive pulse. the bit coding is shown in table 28-9 on page 200 . when pulsing wr or oe , the command loaded determines the action executed. the different commands are shown in table 28-10 on page 201 . table 28-11 on page 210 shows the parallel programming characteristics. figure 28-1. parallel programming v fet +4 - 25v gnd xtal1 data reset v pp bs1 xa0 xa1 oe rdy/bsy pagel wr bs2 v reg v cc (3.3v) pv1 batt pvt see "enter programming mode"
200 2548f?avr?03/2013 atmega406 table 28-7. pin name mapping signal name in programming mode pin name i/o function bs2 pa0 i byte select 2 (?0? selects low byte, ?1? selects 2?nd high byte). rdy/bsy pa1 o 0: device is busy programming, 1: device is ready for new command. oe pa2 i output enable (active low). wr pa3 i write pulse (active low). bs1 pa4 i byte select 1 (?0? selects low byte, ?1? selects high byte). xa0 pa5 i xtal action bit 0 xa1 pa6 i xtal action bit 1 pagel pa7 i program memory and eeprom data page load. data pb7:0 i/o bi-directional data bus (output when oe is low). table 28-8. pin values used to enter programming mode pin symbol value pagel prog_enable[3] 0 xa1 prog_enable[2] 0 xa0 prog_enable[1] 0 bs1 prog_enable[0] 0 table 28-9. xa1 and xa0 coding xa1 xa0 action when xtal1 is pulsed 00 load flash or eeprom address (high or low address byte determined by bs1). 0 1 load data (high or low data byte for flash determined by bs1). 1 0 load command 1 1 no action, idle
201 2548f?avr?03/2013 atmega406 28.6.3 enter programming mode the following algorithm puts the device in parallel programming mode: 1. make sure the chip is started as explained in section 9.2.1 ?power-on reset and charger connect? on page 40 . 2. set reset to ?0? and toggle xtal1 at least six times. 3. set the prog_enable pins listed in table 28-8 on page 200 to ?0000? and wait at least 100 ns. 4. apply 11.5 - 12.5v to reset . any activity on prog_enable pins within 100 ns after +12v has been applied to reset , will cause the device to fail entering progr amming mode. 5. wait at least 50 s before sending a new command. 28.6.4 chip erase the chip erase will erase the flash and eeprom (1) memories plus lock bits. the lock bits are not reset until the program memory has been completely erased. the fuse bits are not changed. a chip erase must be perfor med before the flas h and/or eeprom are reprogrammed. note: 1. the eeprpom memory is preserved during chip erase if the eesave fuse is programmed. load command ?chip erase? 1. set xa1, xa0 to ?10?. this enables command loading. 2. set bs1 to ?0?. 3. set data to ?1000 0000?. this is the command for chip erase. 4. give xtal1 a positive puls e. this loads the command. 5. give wr a negative pulse. this st arts the chip erase. rdy/bsy goes low. 6. wait until rdy/bsy goes high before loading a new command. table 28-10. command byte bit coding command byte command executed 1000 0000 chip erase 0100 0000 write fuse bits 0010 0000 write lock bits 0001 0000 write flash 0001 0001 write eeprom 0000 1000 read signature bytes and calibration byte 0000 0100 read fuse and lock bits 0000 0010 read flash 0000 0011 read eeprom
202 2548f?avr?03/2013 atmega406 28.6.5 programming the flash the flash is organized in pages, see table 28-5 on page 198 . when programming the flash, the program data is latched into a page buffer. this allows one page of program data to be pro- grammed simultaneously. the following procedure describes how to program the entire flash memory: a. load command ?write flash? 1. set xa1, xa0 to ?10?. this enables command loading. 2. set bs1 to ?0?. 3. set data to ?0001 0000?. this is the command for write flash. 4. give xtal1 a positive puls e. this loads the command. b. load address low byte 1. set xa1, xa0 to ?00?. this enables address loading. 2. set bs1 to ?0?. this selects low address. 3. set data = address low byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the address low byte. c. load data low byte 1. set xa1, xa0 to ?01?. this enables data loading. 2. set data = data low byte (0x00 - 0xff). 3. give xtal1 a positive pulse. this loads the data byte. d. load data high byte 1. set bs1 to ?1?. this selects high data byte. 2. set xa1, xa0 to ?01?. this enables data loading. 3. set data = data high byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the data byte. e. latch data 1. set bs1 to ?1?. this selects high data byte. 2. give pagel a positive pulse. this latches the data bytes. (see figure 28-3 for signal waveforms) f. repeat b through e until the entire buffer is f illed or until all data withi n the page is loaded. while the lower bits in the address are mapped to words within the page, the higher bits address the pages within the flash . this is illustrated in figure 28-2 on page 203 . note that if less than eight bits are required to address words in the page (pagesize < 256), the most significant bit(s) in the address low byte are used to address the page when performing a page write. g. load address high byte 1. set xa1, xa0 to ?00?. this enables address loading. 2. set bs1 to ?1?. this selects high address. 3. set data = address high byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the address high byte.
203 2548f?avr?03/2013 atmega406 h. program page 1. give wr a negative pulse. this starts progra mming of the entire page of data. rdy/bsy goes low. 2. wait until rdy/bsy goes high (see figure 28-3 for signal waveforms). i. repeat b through h until the entire flash is programmed or until all data has been programmed. j. end page programming 1. 1. set xa1, xa0 to ?10?. this enables command loading. 2. set data to ?0000 0000?. this is the command for no operation. 3. give xtal1 a positive pulse. this loads the command, and the internal write signals are reset. figure 28-2. addressing the flash which is organized in pages (1) note: 1. pcpage and pcword are listed in table 28-5 on page 198 . program memory word address within a page page address within the flash instruction word pag e pcword[pagemsb:0]: 00 01 02 pageend pag e pcword pcpage pcmsb pagemsb program counter
204 2548f?avr?03/2013 atmega406 figure 28-3. programming the flash waveforms (1) note: 1. ?xx? is don?t care. the letters re fer to the programming description above. 28.6.6 programming the eeprom the eeprom is organized in pages, see table 28-6 on page 198 . when programming the eeprom, the program data is latche d into a page buffer. this al lows one page of data to be programmed simultaneously. th e programming algorithm for th e eeprom data memory is as follows (refer to ?programming the flash? on page 202 for details on command, address and data loading): 1. a: load command ?0001 0001?. 2. g: load address high byte (0x00 - 0xff). 3. b: load address low byte (0x00 - 0xff). 4. c: load data (0x00 - 0xff). 5. e: latch data (give pagel a positive pulse). k: repeat 3 through 5 until the entire buffer is filled. l: program eeprom page 1. set bs to ?0?. 2. give wr a negative pulse. this starts pr ogramming of the eeprom page. rdy/bsy goes low. 3. wait until to rdy/bsy goes high before programming the next page (see figure 28-4 for signal waveforms). rdy/bsy wr oe reset +12v pagel bs2 0x10 addr. low addr. high data data low data high addr. low data low data high xa1 xa0 bs1 xtal1 xx xx xx abcdeb cdegh f
205 2548f?avr?03/2013 atmega406 figure 28-4. programming the eeprom waveforms 28.6.7 reading the flash the algorithm for reading the flash memory is as follows (refer to ?programming the flash? on page 202 for details on command and address loading): 1. a: load command ?0000 0010?. 2. g: load address high byte (0x00 - 0xff). 3. b: load address low byte (0x00 - 0xff). 4. set oe to ?0?, and bs1 to ?0?. the flash word low byte can now be read at data. 5. set bs to ?1?. the flash word high byte can now be read at data. 6. set oe to ?1?. 28.6.8 reading the eeprom the algorithm for reading the eeprom memory is as follows (refer to ?programming the flash? on page 202 for details on command and address loading): 1. a: load command ?0000 0011?. 2. g: load address high byte (0x00 - 0xff). 3. b: load address low byte (0x00 - 0xff). 4. set oe to ?0?, and bs1 to ?0 ?. the eeprom data byte can now be read at data. 5. set oe to ?1?. rdy/bsy wr oe reset +12v pagel bs2 0x11 addr. high data addr. low data addr. low data xx xa1 xa0 bs1 xtal1 xx agbceb c el k
206 2548f?avr?03/2013 atmega406 28.6.9 programming the fuse low bits the algorithm for programming the fuse low bits is as follows (refer to ?programming the flash? on page 202 for details on command and data loading): 1. a: load command ?0100 0000?. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. give wr a negative pulse and wait for rdy/bsy to go high. 28.6.10 programming the fuse high bits the algorithm for programming the fuse high bits is as follows (refer to ?programming the flash? on page 202 for details on command and data loading): 1. a: load command ?0100 0000?. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. set bs1 to ?1? and bs2 to ?0?. this selects high data byte. 4. give wr a negative pulse and wait for rdy/bsy to go high. 5. set bs1 to ?0?. this selects low data byte. figure 28-5. programming the fuses waveforms 28.6.11 programming the lock bits the algorithm for programming the lock bits is as follows (refer to ?programming the flash? on page 202 for details on command and data loading): 1. a: load command ?0010 0000?. 2. c: load data low byte. bit n = ?0? programs the lock bit. if lb mode 3 is programmed (lb1 and lb2 is programmed), it is not possible to program the boot lock bits by any external programming mode. 3. give wr a negative pulse and wait for rdy/bsy to go high. the lock bits can only be cleared by executing chip erase. rdy/bsy wr oe reset +12v pagel 0x40 data data xx xa1 xa0 bs1 xtal1 ac 0x40 data xx ac write fuse low byte write fuse high byte bs2
207 2548f?avr?03/2013 atmega406 28.6.12 reading the fuse and lock bits the algorithm for reading the fuse and lock bits is as follows (refer to ?programming the flash? on page 202 for details on command loading): 1. a: load command ?0000 0100?. 2. set oe to ?0?, bs2 to ?0? and bs1 to ?0?. the status of the fuse low bits can now be read at data (?0? means programmed). 3. set oe to ?0?, bs2 to ?1? and bs1 to ?1?. the status of the fuse high bits can now be read at data (?0? means programmed). 4. set oe to ?0?, bs2 to ?0? and bs1 to ?1?. the status of the lock bits can now be read at data (?0? means programmed). 5. set oe to ?1?. figure 28-6. mapping between bs1, bs2 and the fuse and lock bits during read 28.6.13 reading the signature bytes the algorithm for reading the signatur e bytes is as follows (refer to ?programming the flash? on page 202 for details on command and address loading): 1. a: load command ?0000 1000?. 2. b: load address low byte (0x00 - 0x02). 3. set oe to ?0?, and bs to ?0?. the selected signature byte can now be read at data. 4. set oe to ?1?. 28.6.14 reading the calibration byte the algorithm for reading the calibrati on byte is as follows (refer to ?programming the flash? on page 202 for details on command and address loading): 1. a: load command ?0000 1000?. 2. b: load address low byte, 0x00. 3. set oe to ?0?, and bs1 to ?1?. the calibration byte can now be read at data. 4. set oe to ?1?. lock bits 0 1 bs2 fuse high byte 0 1 bs1 data fuse low byte 0 1 bs2 0
208 2548f?avr?03/2013 atmega406 28.6.15 parallel programming characteristics figure 28-7. parallel programming timing, including some general timing requirements figure 28-8. parallel programming timing, loading sequence with timing requirements (1) note: 1. the timing requirements shown in figure 28-7 (i.e., t dvxh , t xhxl , and t xldx ) also apply to load- ing operation. data & contol (data, xa0/1, bs1, bs2) xtal1 t xhxl t wlwh t dvxh t xldx t plwl t wlrh wr rdy/bsy pagel t phpl t plbx t bvph t xlwl t wlbx t bvwl wlrl xtal1 pagel t plxh xlxh t t xlph addr0 (low byte) data (low byte) data (high byte) addr1 (low byte) data bs1 xa0 xa1 load address (low byte) load data (low byte) load data (high byte) load data load address (low byte)
209 2548f?avr?03/2013 atmega406 figure 28-9. parallel programming timing, reading sequence (within the same page) with timing requirements (1) note: 1. the timing requirements shown in figure 28-7 (i.e., t dvxh , t xhxl , and t xldx ) also apply to read- ing operation. xtal1 oe addr0 (low byte) data (low byte) data (high byte) addr1 (low byte) data bs1 xa0 xa1 load address (low byte) read data (low byte) read data (high byte) load address (low byte) t bvdv t oldv t xlol t ohdz
210 2548f?avr?03/2013 atmega406 notes: 1. t wlrh is valid for the write flash, write eeprom , write fuse bits and write lock bits commands. 2. t wlrh_ce is valid for the chip erase command. table 28-11. parallel programming characteristics symbol parameter min typ max units v pp programming enable voltage (reset input) 11.5 12.5 v i pp programming enable current 250 ? a t dvxh data and control valid before xtal1 high 67 ns t xlxh xtal1 low to xtal1 high 200 ns t xhxl xtal1 pulse width high 150 ns t xldx data and control hold after xtal1 low 67 ns t xlwl xtal1 low to wr low 0 ns t xlph xtal1 low to pagel high 0 ns t plxh pagel low to xtal1 high 150 ns t bvph bs1 valid before pagel high 67 ns t phpl pagel pulse width high 150 ns t plbx bs1 hold after pagel low 67 ns t wlbx bs2/1 hold after wr low 67 ns t plwl pagel low to wr low 67 ns t bvwl bs1 valid to wr low 67 ns t wlwh wr pulse width low 150 ns t wlrl wr low to rdy/bsy low 0 1 ? s t wlrh wr low to rdy/bsy high (1) 3.7 4.5 ms t wlrh_ce wr low to rdy/bsy high for chip erase (2) 7.5 9 ms t xlol xtal1 low to oe low 0 ns t bvdv bs1 valid to data valid 0 250 ns t oldv oe low to data valid 250 ns t ohdz oe high to data tri-stated 250 ns
211 2548f?avr?03/2013 atmega406 28.7 programming via the jtag interface programming through the jtag interface requires control of the four jtag specific pins: tck, tms, tdi, and tdo. control of the re set and clock pins is not required. to be able to use the jtag interface, the jtag en fuse must be programmed. the device is default shipped with the fuse programmed. in addi tion, the jtd bit in mcucsr must be cleared. alternatively, if the jtd bit is set, the external reset can be fo rced low. then, the jtd bit will be cleared after two chip clocks, and the jtag pins are available for programming. this provides a means of using the jtag pins as normal port pi ns in running mode while still allowing in-sys- tem programming via the jtag interface. note th at this technique can not be used when using the jtag pins for boundary-scan or on-chip debug. in these cases the jtag pins must be ded- icated for this purpose. as a definition in this datasheet, the lsb is shifted in and out first of all shift registers. 28.7.1 programming specific jtag instructions the instruction register is 4- bit wide, supporting up to 16 instru ctions. the jtag instructions useful for programming are listed below. the opcode for each instruction is shown behind the instruction name in hex format. the text describes which data register is selected as path between tdi and tdo for each instruction. the run-test/idle state of the tap controller is used to generate internal clocks. it can also be used as an idle state between jtag sequences . the state machine sequence for changing the instruction word is shown in figure 28-10 .
212 2548f?avr?03/2013 atmega406 figure 28-10. state machine sequence for changing the instruction word 28.7.2 avr_reset (0xc) the avr specific public jtag in struction for setting the avr devi ce in the reset mode or taking the device out from the reset mode. the tap cont roller is not reset by th is instruction. the one bit reset register is selected as data register. note that the reset will be active as long as there is a logic ?one? in the reset chain. the output from this chain is not latched. the active states are: ? shift-dr: the reset register is shifted by the tck input. 28.7.3 prog_enable (0x4) the avr specific public jtag instruction for enabling programming via the jtag port. the 16- bit programming enable register is selected as data register. the active states are the following: ? shift-dr: the programming enable signature is shifted into the data register. ? update-dr: the programming enable signature is compared to the correct value, and programming mode is entered if the signature is valid. test-logic-reset run-test/idle shift-dr exit1-dr pause-dr exit2-dr update-dr select-ir scan capture-ir shift-ir exit1-ir pause-ir exit2-ir update-ir select-dr scan capture-dr 0 1 0 11 1 00 00 11 1 0 1 1 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1
213 2548f?avr?03/2013 atmega406 28.7.4 prog_commands (0x5) the avr specific public jtag instruction for entering programming commands via the jtag port. the 15-bit programming command register is selected as data regi ster. the active states are the following: ? capture-dr: the result of the previous command is loaded into the data register. ? shift-dr: the data register is shifted by the tc k input, shifting out the result of the previous command and shifting in the new command. ? update-dr: the programming command is applied to the flash inputs ? run-test/idle: one clock cycle is generated , executing the applied command (not always required, see table 28-12 below). 28.7.5 prog_pageload (0x6) the avr specific public jtag in struction to directly load the fl ash data page via the jtag port. an 8-bit flash data byte register is selected as the data register. this is physically the 8 lsbs of the programming command register. the active states are the following: ? shift-dr: the flash data byte register is shifted by the tck input. ? update-dr: the content of the flash data byte re gister is copied into a temporary register. a write sequence is init iated that within 11 tck cycles loads the content of the temporary register into the flash page buffer. the avr automatically alternates between writing the low and the high byte for each new update-dr state, starti ng with the low byte for the first update-dr encountered after entering the prog_pageload command. the program counter is pre- incremented before writing the low byte, except fo r the first written byte. this ensures that the first data is written to the address set up by prog_commands, and loading the last location in the page buffer does not make the program counter increment into the next page. 28.7.6 prog_pageread (0x7) the avr specific public jtag instruction to dire ctly capture the flash c ontent via the jtag port. an 8-bit flash data byte register is selected as the data register. this is physically the 8 lsbs of the programming command register. the active states are the following: ? capture-dr: the content of the selected flash byte is captured into the flash data byte register. the avr automatically alternates betwe en reading the low and the high byte for each new capture-dr state, starting with the low byte for the first capture-dr encountered after entering the prog_pageread command. the pr ogram counter is post-incremented after reading each high byte, including the first read byte . this ensures that the first data is captured from the first address set up by prog_commands, and reading the last location in the page makes the program counter increment into the next page. ? shift-dr: the flash data byte register is shifted by the tck input. 28.7.7 data registers the data registers are selected by the jtag instruction registers described in section ?program- ming specific jtag instructions? on page 211 . the data registers relevant for programming operations are: ? reset register ? programming enable register ? programming command register ? flash data byte register
214 2548f?avr?03/2013 atmega406 28.7.8 reset register the reset register is a test data register used to reset the part during programming. it is required to reset the part before entering programming mode. a high value in the reset register corresponds to pulling the external reset low. the part is reset as long as there is a high val ue present in the reset register. depending on the fuse settings for the clock options, the part will remain reset for a re set time-out period (refer to ?clock sources? on page 26 ) after releasing the reset register. the output from this data register is not latched, so the reset will take place immediately, as shown in figure 9-1 on page 40 . 28.7.9 programming enable register the programming enable register is a 16-bit register. the content s of this register is compared to the programming enable signature, binary code 0b1010_0011_0111_0000. when the con- tents of the register is equal to the program ming enable signature, programming via the jtag port is enabled. the register is reset to 0 on power-on reset, and should always be reset when leaving programming mode. figure 28-11. programming enable register 28.7.10 programming command register the programming command register is a 15-bit regist er. this register is us ed to serially shift in programming commands, and to serially shift out th e result of the previous command, if any. the jtag programming instruction set is shown in table 28-12 . the state sequence when shifting in the programming commands is illustrated in figure 28-13 . tdi tdo d a t a = dq clockdr & prog_enable programming enable 0xa370
215 2548f?avr?03/2013 atmega406 figure 28-12. programming command register tdi tdo s t r o b e s a d d r e s s / d a t a flash eeprom fuses lock bits table 28-12. jtag programming instruction set a = address high bits, b = address low bits, h = 0 - low byte, 1 - high byte, o = data out, i = data in, x = don?t care instruction tdi sequence tdo sequence notes 1a. chip erase 0100011_10000000 0110001_10000000 0110011_10000000 0110011_10000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx 1b. poll for chip erase complete 0110011_10000000 xxxxx o x_xxxxxxxx (2) 2a. enter flash write 0100011_00010000 xxxxxxx_xxxxxxxx 2b. load address high byte 0000111_ aaaaaaaa xxxxxxx_xxxxxxxx (9) 2c. load address low byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 2d. load data low byte 0010011_ iiiiiiii xxxxxxx_xxxxxxxx 2e. load data high byte 0010111_ iiiiiiii xxxxxxx_xxxxxxxx 2f. latch data 0110111_00000000 1110111_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 2g. write flash page 0110111_00000000 0110101_00000000 0110111_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 2h. poll for page write complete 0110111_00000000 xxxxx o x_xxxxxxxx (2) 3a. enter flash read 0100011_00000010 xxxxxxx_xxxxxxxx 3b. load address high byte 0000111_ aaaaaaaa xxxxxxx_xxxxxxxx (9) 3c. load address low byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx
216 2548f?avr?03/2013 atmega406 3d. read data low and high byte 0110010_00000000 0110110_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo xxxxxxx_ oooooooo low byte high byte 4a. enter eeprom write 0100011_00010001 xxxxxxx_xxxxxxxx 4b. load address high byte 0000111_ aaaaaaaa xxxxxxx_xxxxxxxx (9) 4c. load address low byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 4d. load data byte 0010011_ iiiiiiii xxxxxxx_xxxxxxxx 4e. latch data 0110111_00000000 1110111_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 4f. write eeprom page 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 4g. poll for page write complete 0110011_00000000 xxxxx o x_xxxxxxxx (2) 5a. enter eeprom read 0100011_00000011 xxxxxxx_xxxxxxxx 5b. load address high byte 0000111_ aaaaaaaa xxxxxxx_xxxxxxxx (9) 5c. load address low byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 5d. read data byte 0110011_ bbbbbbbb 0110010_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo 6a. enter fuse write 0100011_01000000 xxxxxxx_xxxxxxxx 6b. load data high byte (6) 0010011_ iiiiiiii xxxxxxx_xxxxxxxx (3) 6c. write fuse high byte 0110111_00000000 0110101_00000000 0110111_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 6d. poll for fuse write complete 0110111_00000000 xxxxx o x_xxxxxxxx (2) 6e. load data low byte (7) 0010011_ iiiiiiii xxxxxxx_xxxxxxxx (3) 6f. write fuse low byte 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 6g. poll for fuse write complete 0110011_00000000 xxxxx o x_xxxxxxxx (2) 7a. enter lock bit write 0100011_00100000 xxxxxxx_xxxxxxxx 7b. load data byte (8) 0010011_11 iiiiii xxxxxxx_xxxxxxxx (4) table 28-12. jtag programming instruction (continued) set (continued) a = address high bits, b = address low bits, h = 0 - low byte, 1 - high byte, o = data out, i = data in, x instruction tdi sequence tdo sequence notes
217 2548f?avr?03/2013 atmega406 notes: 1. this command sequence is not required if the seven msb are correctly set by the previo us command sequence (which is normally the case). 2. repeat until o = ?1?. 3. set bits to ?0? to program the corresponding fuse, ?1? to unprogram the fuse. 4. set bits to ?0? to program the corresponding lock bit, ?1? to leave the lock bit unchanged. 5. ?0? = programmed, ?1? = unprogrammed. 6. the bit mapping for fuses high byte is listed in table 28-3 on page 196 7. the bit mapping for fuses low byte is listed in table 28-4 on page 197 8. the bit mapping for lock bits byte is listed in table 28-1 on page 195 9. address bits exceeding pcmsb and eeamsb ( table 28-5 and table 28-6 ) are don?t care 10. all tdi and tdo sequences are repr esented by binary digits (0b...). 7c. write lock bits 0110011_00000000 0110001_00000000 0110011_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx (1) 7d. poll for lock bit write complete 0110011_00000000 xxxxx o x_xxxxxxxx (2) 8a. enter fuse/lock bit read 0100011_00000100 xxxxxxx_xxxxxxxx 8b. read fuse high byte (6) 0111110_0 0000000 0111111_0 0000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo 8c. read fuse low byte (7) 0110010_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo 8d. read lock bits (8) 0110110_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xx oooooo (5) 8e. read fuses and lock bits 0111010_00000000 0110010_00000000 0110110_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo xxxxxxx_ oooooooo xxxxxxx_ oooooooo (5) fuse high byte fuse low byte lock bits 9a. enter signature byte read 0100011_00001000 xxxxxxx_xxxxxxxx 9b. load address byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 9c. read signature byte 0110010_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo 10a. enter calibration byte read 0100011_00001000 xxxxxxx_xxxxxxxx 10b. load address byte 0000011_ bbbbbbbb xxxxxxx_xxxxxxxx 10c. read calibration byte 0110110_00000000 0110111_00000000 xxxxxxx_xxxxxxxx xxxxxxx_ oooooooo 11a. load no operation command 0100011_00000000 0110011_00000000 xxxxxxx_xxxxxxxx xxxxxxx_xxxxxxxx table 28-12. jtag programming instruction (continued) set (continued) a = address high bits, b = address low bits, h = 0 - low byte, 1 - high byte, o = data out, i = data in, x instruction tdi sequence tdo sequence notes
218 2548f?avr?03/2013 atmega406 figure 28-13. state machine sequence for changing/reading the data word 28.7.11 flash data byte register the flash data byte register provides an ef ficient way to load t he entire flash page buffer before executing page write, or to read out/ver ify the content of the flash. a state machine sets up the control signals to the flash and senses the strobe signals from the flash, thus only the data words need to be shifted in/out. the flash data byte register actually consists of the 8-bit scan chain and a 8-bit temporary reg- ister. during page load, the update-dr state copies the content of the scan chain over to the temporary register and initiates a write sequence that within 11 tck cycles loads the content of the temporary register into the flash page bu ffer. the avr automatically alternates between writing the low and the high byte for each new up date-dr state, starting with the low byte for the first update-dr encountered after entering t he prog_pageload command. the program counter is pre-incremented before writing the low byte, except for the first written byte. this ensures that the first data is written to th e address set up by prog_commands, and loading the last location in the page buffer does not ma ke the program counter increment into the next page. during page read, the content of the selected flash byte is captured into the flash data byte register during the capture-dr state. the avr automatically alternates between reading the low and the high byte for each new capture-dr stat e, starting with the low byte for the first cap- test-logic-reset run-test/idle shift-dr exit1-dr pause-dr exit2-dr update-dr select-ir scan capture-ir shift-ir exit1-ir pause-ir exit2-ir update-ir select-dr scan capture-dr 0 1 0 11 1 00 00 11 1 0 1 1 0 1 0 0 1 0 1 1 0 1 0 0 0 0 1 1
219 2548f?avr?03/2013 atmega406 ture-dr encountered after entering the pr og_pageread command. the program counter is post-incremented after reading each high byte, incl uding the first read byte. this ensures that the first data is captured from the first ad dress set up by prog_commands, and reading the last location in the page makes the progra m counter increment into the next page. figure 28-14. flash data byte register the state machine controlling the flash data by te register is clocked by tck. during normal operation in which eight bits are shifted for eac h flash byte, the clock cycles needed to navigate through the tap controller automatically feeds th e state machine for the flash data byte regis- ter with sufficient number of clock pulses to complete its operation transparently for the user. however, if too few bits are shifted between each update-dr state during page load, the tap controller should stay in the run-test/idle state for some tck cycles to en sure that there are at least 11 tck cycles between each update-dr state. 28.7.12 programming algorithm all references below of type ?1a?, ?1b?, and so on, refer to table 28-12 . 28.7.13 entering programming mode 1. enter jtag instruction avr_reset and shift 1 in the reset register. 2. enter instruction prog_enable and shift 0b1010_0011_0111_0000 in the program- ming enable register. 28.7.14 leaving programming mode 1. enter jtag instruction prog_commands. 2. disable all programming instructions by using no operation instruction 11a. 3. enter instruction prog_enable and shift 0b0000_0000_0000_0000 in the program- ming enable register. 4. enter jtag instruction avr_reset and shift 0 in the reset register. tdi tdo d a t a flash eeprom fuses lock bits strobes address state machine
220 2548f?avr?03/2013 atmega406 28.7.15 performing chip erase 1. enter jtag instruction prog_commands. 2. start chip erase using programming instruction 1a. 3. poll for chip erase complete using prog ramming instruction 1b, or wait for t wlrh_ce (refer to table 28-11 on page 210 ). 28.7.16 programming the flash 1. enter jtag instruction prog_commands. 2. enable flash write using programming instruction 2a. 3. load address high byte using programming instruction 2b. 4. load address low byte using programming instruction 2c. 5. load data using programming instructions 2d, 2e and 2f. 6. repeat steps 4 and 5 for all instruction words in the page. 7. write the page using programming instruction 2g. 8. poll for flash write complete using prog ramming instruction 2h, or wait for t wlrh (refer to table 28-11 on page 210 ). 9. repeat steps 3 to 7 until all data have been programmed. a more efficient data transfer can be achieved using the prog_pageload instruction: 1. enter jtag instruction prog_commands. 2. enable flash write using programming instruction 2a. 3. load the page address using programming instructions 2b and 2c. pcword (refer to table 28-5 on page 198 ) is used to address within one page and must be written as 0. 4. enter jtag instruction prog_pageload. 5. load the entire page by shifting in all inst ruction words in the page byte-by-byte, starting with the lsb of the first inst ruction in the page and ending with the msb of the last instruction in the page. use update-dr to copy the contents of the flash data byte reg- ister into the flash page location and to auto-increment the program counter before each new word. 6. enter jtag instruction prog_commands. 7. write the page using programming instruction 2g. 8. poll for flash write complete using prog ramming instruction 2h, or wait for t wlrh (refer to table 28-11 on page 210 ). 9. repeat steps 3 to 8 until all data have been programmed. 28.7.17 reading the flash 1. enter jtag instruction prog_commands. 2. enable flash read using programming instruction 3a. 3. load address using programming instructions 3b and 3c. 4. read data using programming instruction 3d. 5. repeat steps 3 and 4 until all data have been read. a more efficient data transfer can be achieved usi ng the prog_pageread instruction: 1. enter jtag instruction prog_commands. 2. enable flash read using programming instruction 3a. 3. load the page address using programming instructions 3b and 3c. pcword (refer to table 28-5 on page 198 ) is used to address within one page and must be written as 0.
221 2548f?avr?03/2013 atmega406 4. enter jtag instruction prog_pageread. 5. read the entire page (or flash) by shifting out all instruction words in the page (or flash), starting with the lsb of the first instruction in the page (flash) and ending with the msb of the last instruction in the page (flash). the capture-dr state both captures the data from the flash, and also auto-increments th e program counter after each word is read. note that capture-dr comes before the shift- dr state. hence, the first byte which is shifted out contains valid data. 6. enter jtag instruction prog_commands. 7. repeat steps 3 to 6 until all data have been read. 28.7.18 programming the eeprom 1. enter jtag instruction prog_commands. 2. enable eeprom write usin g programming instruction 4a. 3. load address high byte using programming instruction 4b. 4. load address low byte using programming instruction 4c. 5. load data using programming instructions 4d and 4e. 6. repeat steps 4 and 5 for all data bytes in the page. 7. write the data using programming instruction 4f. 8. poll for eeprom write comple te using programming instru ction 4g, or wait for t wlrh (refer to table 28-11 on page 210 ). 9. repeat steps 3 to 8 until all data have been programmed. note that the prog_pageload instruction can not be used when programmi ng the eeprom. 28.7.19 reading the eeprom 1. enter jtag instruction prog_commands. 2. enable eeprom read using programming in struction 5a. 3. load address using programming instructions 5b and 5c. 4. read data using programming instruction 5d. 5. repeat steps 3 and 4 until all data have been read. note that the prog_pageread instruction can not be us ed when reading the eeprom. 28.7.20 programming the fuses 1. enter jtag instruction prog_commands. 2. enable fuse write using programming instruction 6a. 3. load data high byte using programming instruct ions 6b. a bit valu e of ?0? will program the corresponding fuse, a ?1? will unprogram the fuse. 4. write fuse high byte using programming instruction 6c. 5. poll for fuse write complete using prog ramming instruction 6d, or wait for t wlrh (refer to table 28-11 on page 210 ). 6. load data low byte using pr ogramming instructions 6e. a ?0? will program the fuse, a ?1? will unprogram the fuse. 7. write fuse low byte using programming instruction 6f. 8. poll for fuse write complete using prog ramming instruction 6g, or wait for t wlrh (refer to table 28-11 on page 210 ).
222 2548f?avr?03/2013 atmega406 28.7.21 programming the lock bits 1. enter jtag instruction prog_commands. 2. enable lock bit write using programming instruction 7a. 3. load data using pr ogramming instructions 7b. a bit va lue of ?0? will program the corre- sponding lock bit, a ?1? will leave the lock bit unchanged. 4. write lock bits using programming instruction 7c. 5. poll for lock bit write complete using pr ogramming instruction 7d, or wait for t wlrh (refer to table 28-11 on page 210 ). 28.7.22 reading the fuses and lock bits 1. enter jtag instruction prog_commands. 2. enable fuse/lock bit read using programming instruction 8a. 3. to read all fuses and lock bits, use programming instruction 8e. to only read fuse high byte, use programming instruction 8b. to only read fuse low byte, use programming instruction 8c. to only read lock bits, use programming instruction 8d. 28.7.23 reading the signature bytes 1. enter jtag instruction prog_commands. 2. enable signature byte read using programming instruction 9a. 3. load address 0x00 using programming instruction 9b. 4. read first signature byte using programming instruction 9c. 5. repeat steps 3 and 4 with address 0x01 and address 0x02 to read the second and third signature bytes, respectively. 28.7.24 reading the calibration byte 1. enter jtag instruction prog_commands. 2. enable calibration byte read using programming instruction 10a. 3. load address 0x00 using programming instruction 10b. 4. read the calibration byte using programming instruction 10c.
223 2548f?avr?03/2013 atmega406 29. operating circuit figure 29-1. operating circuit diagram rp rn rp rp rp rp rsense rpi rni ci rpc rpf rcf rdf rled rled rled rled rled atmega406 + nv ppi pi ni pa 4 pa 3 pa 2 xtal2 reset xtal1 vreg sck pb4 pb3 pb0 pb1 pb2 sda gnd - creg 1 creg 2 v cc 100 100 smb clo ck smb da ta rp1 rp2 sgnd vref vrefgnd rt4 rt3 rt2 pa 1 rnni nni ci ci rppi cp cp cp cp pv1 pv2 pv3 pv4 pvt od oc batt vfet opc rt1 pa0/adc0 r1 cxtal2 cxtal 2 creset cref
224 2548f?avr?03/2013 atmega406 table 29-1. recommended values for external devices note: 1. the sense resistor should be adjusted to the current flow for the application. 2. the pre-charger resistor should be adjusted to the pre-charger curret flow for the application. symbol use parameter min typ max unit r1 pull-up resistor for thermistors r 10 k ? rt1 rt2 rt3 rt4 ntc thermistor r@25 ? c10k ? b-constant 3000 4000 k r s source impedance when using pa0...4 as v-adc inputs r037k ? worst gain-error due to r s 012% r nni r ppi current protection lp-filter resistor r1k ? r ni r pi current sense lp-filter resistors r 10 100 500 ? c i current sense lp-filter capasitor c0.010.10.4f (r pi -r ni )*c i current sense lp-filter time constant ? 10 20 s r sense (1) current sense resistor r 5 m ? rp cell input lp-filter resistor r 10 500 1000 ? cp cell input lp-filter capacitor c 0.01 0.1 0.5 f rp*cp cell input lp-filter time constant ? 6.5 25 100 s rn pull-up resistor r 0 10 tbd ? r df r cf r pf pull-up resistors r 1 m ? r pc (2) pre-charge resistor r 1 k ? cref vref decoupling c 1 1 22 f creg1 creg2 vreg charge-storage c 0.1 f 1 rp1 rp2 twi pull-up resistors c 2.2 m ? creset c 0.1 f
225 2548f?avr?03/2013 atmega406 30. electrical characteristics 30.1 absolute maximum ratings* 30.2 dc characteristics operating temperature......................................-30 ? c to +85 ? c *notice: stresses beyond those listed under ?absolute maximum ratings? may cause permanent dam- age to the device. this is a stress rating only and functional operation of the device at these or other conditions beyond those indicated in the operational sections of th is specification is not implied. exposure to absolute maximum rating conditions for extended periods may affect device reliability. storage temperature ..................................... -65c to +150c voltage on pa0 - pa7, pb0 - pb7, pd0 - pd1, vcc, pi, ppi, ni, nn i, xtal1, and xtal2 with respect to ground ............................. -0.5v to v reg +0.5v voltage on scl, sda, nv, pv1 and reset with respect to ground .....................................-0.5v to + 6.0v voltage on pvt and vfet with respect to ground ......................................-0.5v to + 35v voltage on pc0, opc, oc and batt with respect to ground ...........................-0.5v to vfet + 0.5v voltage on od, pv2 - pv4 with respect to ground .............................-0.5v to pvt + 0.5v maximum operating voltage ............................................. 25v dc characteristics, t a = -30 ? c to 85 ? c, v cc = 3.3v parameter condition min typ max unit supply current power supply current active 1.2 ma idle 270 ? a adc noise reduction 220 ? a power-save 35 ? a power-down 20 ? a power-off 1.5 ? a voltage regulator (1) regulated output voltage (2) i out = 5 ma 3.25 3.3 3.35 v temperature stability (2) i out = 5 ma t a = 0 - 60 ? c 5 15 mv i out = 5 ma t a = -30 ? 85 ? c 20 70 mv load regulation 0.1 ma < i out < 5 ma 20 60 mv line regulation 4v < v fet < 25v, i out = 1 ma 2 10 mv vref reference voltage 1.1 v ref. voltage accuracy after calibration, at calibration temperature 0.1 0.2 % temperature drift (3) t a = -30 ? 60 ? c 80 ppm/ ? c
226 2548f?avr?03/2013 atmega406 v-adc reference voltage 1.100 v conversion time 519 ? s effective resolution 12 bits 1 lsb un-scaled inputs 269 ? v 1 lsb scaled inputs (x 0.2) 1.34 mv inl 1 3 lsb input voltage range adc0, adc1, adc2, adc3, vtemp 01v adc4 0 5 v cell1 2 5 v cell2, pv1 2v 0 5 v cell3, pv1 2v 0 5 v cell4, pv1 2v 0 5 v offset 1.6 mv gain error cell inputs (5) 1 0.5 % cc-adc reference voltage 220 mv conversion time and resolution 53.7 ? v resolution 3.9 ms 1.68 ? v resolution 125 1000 ms inl 1000 ms conversion time 4 lsb cc-adc offset (6) uncompensated 50 200 ? v cc-adc offset drift (4) t a = 0 - 60 ? c 1 15 ? v cc-adc gain error 1 ? temperature sensor v ptat , voltage proportional to absolute temperature 0.6 mv/k absolute accuracy (3) 4 k fet driver |v gs_on |1115v oc/od rise time (10 - 90%) (switching off) cl = 10 nf 10 50 s oc/od fall time (v gs = 0 - v gs = -5v) (switching on) cl = 10 nf 100 s opc rise time (10 - 90%) (switching off) cl = 1 nf 100 500 s opc fall time (v gs = 0 - v gs = -5v) (switching on) cl = 1 nf 100 500 s dc characteristics, t a = -30 ? c to 85 ? c, v cc = 3.3v (continued) parameter condition min typ max unit
227 2548f?avr?03/2013 atmega406 notes: 1. voltage regulator performance is based on 1 f smooth capacitor. 2. after vref calibration at second temperature. by default the first calibrat ion is performed at 85 ? c in atmel factory test. the second calibration step can easily be implemented in a standard test flow at room temperature. 3. this value is not tested in production. 4. after system offset compensation in software. 5. after software gain error compensation. 6. this value should be measured at system level and stored in eeprom for software offset compensation. slow rc oscillator frequency t a = - 30 ? 85 ? c 165 khz temperature drift 5 % ultra low power rc oscillator frequency t a = - 30 ? 85 ? c 124 khz temperature drift 8 % dc characteristics, t a = -30 ? c to 85 ? c, v cc = 3.3v (continued) parameter condition min typ max unit
228 2548f?avr?03/2013 atmega406 30.3 general i/o lines characteristics 30.3.1 low voltage ports notes: 1. applicable for all except pc0. 2. ?max? means the highest value where the pin is guaranteed to be read as low. 3. ?min? means the lowest value where th e pin is guaranteed to be read as high. 4. although each i/o port can sink more than the test condition s (5 ma at vcc = 3.3v) under steady state conditions (non-tran- sient, the following must be observed: - the sum of all iol should not exceed 20 ma. if iol exceeds the test conditio n, vol may exceed the related sp ecification. pins ar e not guaranteed to sink current greater than the listed test condition. 5. although each i/o port can source more than the test cond itions (2 ma at vcc = 3.3v) under steady state conditions (non- transient, the following must be observed: - the sum of all ioh should not exceed 2 ma. 30.3.2 high voltage ports notes: 1. parameter characterized and not tested. 2. cb = capacitance of one bus line in pf figure 30-1. t a = -30 ? c to 85 ? c, v cc = 3.3v (unless otherwise noted) (1) symbol parameter condition min. typ. max. units v il input low voltage v cc = 3.3v -0.5 0.3v cc (2) v v ih input high voltage v cc = 3.3v 0.6v cc (3) v cc + 0.5 v v ol output low voltage (4) i ol = 5ma, v cc = 3.3v 0.5 v v oh output high voltage (5) i oh = 2 ma, v cc = 3.3v 2.3 v i il input leakage current i/o pin v cc = 3.3v, pin low (absolute value) 1a i ih input leakage current i/o pin v cc = 3.3v, pin high (absolute value) 1a figure 30-2. t a = -30 ? c to 85 ? c, v cc = 3.3v (unless otherwise noted) symbol parameter condition min. typ. max. units v ol (1) output low voltage v cc = 3.3v 0.5 v t r (1) rise time v cc = 3.3v 300 ns t of (1) output fall time from v ihmin to v ilmax cb < 400 pf (2) 200 ns
229 2548f?avr?03/2013 atmega406 30.4 2-wire serial inte rface characteristics table 30-1 describes the requirements for devices connected to the two-wire serial bus. the atmega406 two-wire serial interface meets or exceeds these requirements under the noted conditions. timing symbols refer to figure 30-3 . notes: 1. in atmega406, this parameter is characterized and not tested. 2. c b = capacitance of one bus line in pf. 3. f ck = cpu clock frequency 4. this requirement applies to all atmega406 two-wire serial in terface operation. other devices connected to the two-wire serial bus need only obey the general f scl requirement. table 30-1. two-wire serial bus requirements symbol parameter condition min max units vil input low-voltage -0.5 0.8 v vih input high-voltage 2.1 5.5 v vol (1) output low-voltage 350 a sink current 0 0.4 v tr (1) rise time for both sda and scl 300 ns tof (1) output fall time from v ihmin to v ilmax c b < 400 pf (2) 250 ns tsp (1) spikes suppressed by input filter 0 50 ns i i input current each i/o pin 0.1v bus < v i < 0.9v bus -5 5 a c i (1) capacitance for each i/o pin ? 10 pf f scl scl clock frequency f ck (3) > max(16f scl , 450 khz) (4) 0 100 khz rp value of pull-up resistor f scl ? 100 khz ? t hd;sta hold time (repeated) start condition f scl ? 100 khz 4.0 ? s t low low period of the scl clock f scl ? 100 khz 4.7 ? s t high high period of the scl clock f scl ? 100 khz 4.0 ? s t su;sta set-up time for a repeated start condition f scl ? 100 khz 4.7 ? s t hd;dat data hold time f scl ? 100 khz 0.3 3.45 s t su;dat data setup time f scl ? 100 khz 250 ? ns t su;sto setup time for stop condition f scl ? 100 khz 4.0 ? s t buf bus free time between a stop and start condition f scl ? 100 khz 4.7 ? s v bus 0,4v ? 350a ------------------------------- v bus 0,4v ? 100a -------------------------------
230 2548f?avr?03/2013 atmega406 figure 30-3. two-wire serial bus timing 30.5 reset characteristics notes: 1. power-on reset is issued when a charger is conn ected and the regulator has stable work conditions. 2. values based on characterization. note: internal voltage regulator must be on. note: internal voltage regulator must be on. t su;sta t low t high t low t of t hd;sta t hd;dat t su;dat t su;sto t buf scl sda t r table 30-2. characteristics for powering-up the ldo (1) symbol (2) parameter min typ max units charger present v rot regulator power-on threshold 3.0 4.0 v v cht charge voltage threshold 1.0 v no charger present v rot regulator power-on threshold 3.0 4.0 v v pvit voltage threshold on battery cell 1 2.0 v table 30-3. power-on reset characteristics symbol parameter condition min typ max units v cot charger-on thresholt voltage regulator must operate 6 7 8 v table 30-4. external reset characteristics symbol parameter condition min typ max units v rst reset pin threshold voltage v reg = 3.3v 0.66 2.8 v t rst minimum pulse width on reset pin 900 ns
231 2548f?avr?03/2013 atmega406 30.6 supply current of i/o modules table 30-5 on page 231 is showing the additional current consumption compared to i cc active and i cc idle for every i/o module controlle d by the power reduction register, see ?prr0 ? power reduction register 0? on page 36 for details. the tables and formulas below can be used to calculate the additional current consumption fo r the different i/o modules in active and idle mode. 30.6.0.1 example 1 calculate the expected current consumption in idle mode with timer1, v-adc and battery pro- tection enabled at v cc = 3.3v and f = 1mhz. from table 30-5 , fourth column, we see that we need to add 1.7% for the timer1, 1.9% for th e v-adc, and 25.2% for the twi module. reading from ?dc characteristics? on page 225 , we find that the idle curren t consumption is typically 1.2 ma at v cc = 3.3v and f = 1mhz. the total current consumption in idle mode with usart0, timer1, and spi enabled, gives: table 30-5. additional current consumption for the different i/o modules prr0 bit additional current consumption at v cc = 3.3v, f = 1 mhz [a] additional current consumption compared to active mode [%] additional current consumption compared to idle mode [%] prtwi 68.0 5.6 25.2 prtim1 4.5 0.4 1.7 prtim0 6.0 0.5 2.2 prvadc 5.0 4.2 1.9 i cc total 1.2 ma 1 0.017 0.019 0.252 +++ ?? ? 1.55 ma ??
232 2548f?avr?03/2013 atmega406 31. typical characteris tics ? preliminary the following charts are tested on a few microcont rollers only. these figures are not tested dur- ing manufacturing, and are added for illustration purpose. 31.1 pin pull-up figure 31-1. i/o pin pull-up re sistor current vs. input voltage (v cc = 3.3v) figure 31-2. reset pull-up resi stor current vs. input voltage (v cc = 3.3v) i/o pin pull-up resistor current vs. input voltage v cc = 3.3v 85 ?c 25 ?c -30 ?c 0 10 20 30 40 50 60 70 80 90 0 0,5 1 1,5 2 2,5 3 3,5 v i (v) i op (ua) reset pull-up resistor current vs. reset pin voltage v cc = 3.3v 85 ?c 25 ?c -30 ?c 0 10 20 30 40 50 60 70 80 0 0,5 1 1,5 2 2,5 3 3,5 v reset (v) i reset (ua)
233 2548f?avr?03/2013 atmega406 31.2 pin driver strength figure 31-3. i/o pin putput voltage vs. sink current (v cc = 3.3v) figure 31-4. i/o pin output voltage vs. source current (v cc = 3.3v) i/o pin output voltage vs. sink current v cc = 3.3v 85 ?c 25 ?c -30 ?c 0.4 0.5 0.6 0.7 0.8 0.9 1 1.1 1.2 1.3 0 5 10 15 20 25 i ol (ma) v ol (v) i/o pin output voltage vs. source current v cc = 3.3v 85 ?c 25 ?c -30 ?c 1.5 1.7 1.9 2.1 2.3 2.5 2.7 2.9 0 5 10 15 20 25 i oh (ma) v oh (v)
234 2548f?avr?03/2013 atmega406 31.3 internal oscillator speed figure 31-5. watchdog oscillator freq uency vs. temperature (v cc = 3.3v) figure 31-6. calibrated 1 mhz rc oscillator frequency vs. temperature (v cc = 3.3v) watchdog oscillator frequency vs. temperature v cc = 3.3 v 117 118 119 120 121 122 123 124 125 126 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 temperature f rc (k hz) calibrated 1 mhz rc oscillator frequency vs. temperature v cc = 3.3 v 0.975 0.98 0.985 0.99 0.995 1 1.005 1.01 1.015 1.02 1.025 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 temperature f rc (mhz)
235 2548f?avr?03/2013 atmega406 figure 31-7. calibrated 1 mhz rc oscillator frequency vs. osccal value (v cc = 3.3v) figure 31-8. slow rc oscillator freq uency vs. temperature (v cc = 3.3v) calibrated 1 mhz rc oscillator frequency vs. osccal value 85 ?c 25 ?c -30 ?c 0 0.5 1 1.5 2 2.5 0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256 osccal (x1) f rc (mhz) slow rc oscillator frequency vs. temperature v cc = 3.3 v 153 153.5 154 154.5 155 155.5 156 156.5 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 100 temperature f rc (khz)
236 2548f?avr?03/2013 atmega406 32. register summary address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page (0xff) reserved ? ? ? ? ? ? ? ? (0xfe) reserved ? ? ? ? ? ? ? ? (0xfd) reserved ? ? ? ? ? ? ? ? (0xfc) reserved ? ? ? ? ? ? ? ? (0xfb) reserved ? ? ? ? ? ? ? ? (0xfa) reserved ? ? ? ? ? ? ? ? (0xf9) reserved ? ? ? ? ? ? ? ? (0xf8) bpplr ? ? ? ? ? ? bpple bppl 128 (0xf7) bpcr ? ? ? ? duvd scd dcd ccd 128 (0xf6) cbptr scpt[3:0] ocpt[3:0] 129 (0xf5) bpocd dcdl[3:0] ccdl[3:0] 130 (0xf4) bpscd ? ? ? ? scdl[3:0] 130 (0xf3) bpduv ? ? duvt1 duvt0 dudl[3:0] 131 (0xf2) bpir duvif cocif docif scif duvie cocie docie scie 132 (0xf1) cbcr ? ? ? ? cbe4 cbe3 cbe2 cbe1 137 (0xf0) fcsr ? ? pwmoc pwmopc cps dfe cfe pfd 134 (0xef) reserved ? ? ? ? ? ? ? ? (0xee) reserved ? ? ? ? ? ? ? ? (0xed) reserved ? ? ? ? ? ? ? ? (0xec) reserved ? ? ? ? ? ? ? ? (0xeb) reserved ? ? ? ? ? ? ? ? (0xea) reserved ? ? ? ? ? ? ? ? (0xe9) cadich cadic[15:8] 111 (0xe8) cadicl cadic[7:0] 111 (0xe7) cadrdc cadrdc[7:0] 112 (0xe6) cadrcc cadrcc[7:0] 112 (0xe5) cadcsrb ? cadacie cadrcie cadicie ? cadacif cadrcif cadicif 110 (0xe4) cadcsra caden ? cadub cadas1 cadas0 cadsi1 cadsi0 cadse 109 (0xe3) cadac3 cadac[31:24] 111 (0xe2) cadac2 cadac[23:16] 111 (0xe1) cadac1 cadac[15:8] 111 (0xe0) cadac0 cadac[7:0] 111 (0xdf) reserved ? ? ? ? ? ? ? ? (0xde) reserved ? ? ? ? ? ? ? ? (0xdd) reserved ? ? ? ? ? ? ? ? (0xdc) reserved ? ? ? ? ? ? ? ? (0xdb) reserved ? ? ? ? ? ? ? ? (0xda) reserved ? ? ? ? ? ? ? ? (0xd9) reserved ? ? ? ? ? ? ? ? (0xd8) reserved ? ? ? ? ? ? ? ? (0xd7) reserved ? ? ? ? ? ? ? ? (0xd6) reserved ? ? ? ? ? ? ? ? (0xd5) reserved ? ? ? ? ? ? ? ? (0xd4) reserved ? ? ? ? ? ? ? ? (0xd3) reserved ? ? ? ? ? ? ? ? (0xd2) reserved ? ? ? ? ? ? ? ? (0xd1) bgcrr bgcr7 bgcr6 bgcr5 bgcr4 bgcr3 bgcr2 bgcr1 bgcr0 123 (0xd0) bgccr bgen ? bgcc5 bgcc4 bgcc3 bgcc2 bgcc1 bgcc0 123 (0xcf) reserved ? ? ? ? ? ? ? ? (0xce) reserved ? ? ? ? ? ? ? ? (0xcd) reserved ? ? ? ? ? ? ? ? (0xcc) reserved ? ? ? ? ? ? ? ? (0xcb) reserved ? ? ? ? ? ? ? ? (0xca) reserved ? ? ? ? ? ? ? ? (0xc9) reserved ? ? ? ? ? ? ? ? (0xc8) reserved ? ? ? ? ? ? ? ? (0xc7) reserved ? ? ? ? ? ? ? ? (0xc6) reserved ? ? ? ? ? ? ? ? (0xc5) reserved ? ? ? ? ? ? ? ? (0xc4) reserved ? ? ? ? ? ? ? ? (0xc3) reserved ? ? ? ? ? ? ? ? (0xc2) reserved ? ? ? ? ? ? ? ? (0xc1) reserved ? ? ? ? ? ? ? ? (0xc0) ccsr ? ? ? ? ? ?xoeacs 29
237 2548f?avr?03/2013 atmega406 (0xbf) reserved ? ? ? ? ? ? ? ? (0xbe) twbcsr twbcif twbcie ? ? ? twbdt1 twbdt0 twbcip 169 (0xbd) twamr twam[6:0] ?150 (0xbc) twcr twint twea twsta twsto twwc twen ?twie 147 (0xbb) twdr 2?wire serial interface data register 149 (0xba) twar twa[6:0] twgce 149 (0xb9) twsr tws[7:3] ? twps1 twps0 148 (0xb8) twbr 2?wire serial interface bit rate register 147 (0xb7) reserved ? ? ? ? ? ? ? (0xb6) reserved ? ? ? ? ? ? ? ? (0xb5) reserved ? ? ? ? ? ? ? ? (0xb4) reserved ? ? ? ? ? ? ? ? (0xb3) reserved ? ? ? ? ? ? ? ? (0xb2) reserved ? ? ? ? ? ? ? ? (0xb1) reserved ? ? ? ? ? ? ? ? (0xb0) reserved ? ? ? ? ? ? ? ? (0xaf) reserved ? ? ? ? ? ? ? ? (0xae) reserved ? ? ? ? ? ? ? ? (0xad) reserved ? ? ? ? ? ? ? ? (0xac) reserved ? ? ? ? ? ? ? ? (0xab) reserved ? ? ? ? ? ? ? ? (0xaa) reserved ? ? ? ? ? ? ? ? (0xa9) reserved ? ? ? ? ? ? ? ? (0xa8) reserved ? ? ? ? ? ? ? ? (0xa7) reserved ? ? ? ? ? ? ? ? (0xa6) reserved ? ? ? ? ? ? ? ? (0xa5) reserved ? ? ? ? ? ? ? ? (0xa4) reserved ? ? ? ? ? ? ? ? (0xa3) reserved ? ? ? ? ? ? ? ? (0xa2) reserved ? ? ? ? ? ? ? ? (0xa1) reserved ? ? ? ? ? ? ? ? (0xa0) reserved ? ? ? ? ? ? ? ? (0x9f) reserved ? ? ? ? ? ? ? ? (0x9e) reserved ? ? ? ? ? ? ? ? (0x9d) reserved ? ? ? ? ? ? ? ? (0x9c) reserved ? ? ? ? ? ? ? ? (0x9b) reserved ? ? ? ? ? ? ? ? (0x9a) reserved ? ? ? ? ? ? ? ? (0x99) reserved ? ? ? ? ? ? ? ? (0x98) reserved ? ? ? ? ? ? ? ? (0x97) reserved ? ? ? ? ? ? ? ? (0x96) reserved ? ? ? ? ? ? ? ? (0x95) reserved ? ? ? ? ? ? ? ? (0x94) reserved ? ? ? ? ? ? ? ? (0x93) reserved ? ? ? ? ? ? ? ? (0x92) reserved ? ? ? ? ? ? ? ? (0x91) reserved ? ? ? ? ? ? ? ? (0x90) reserved ? ? ? ? ? ? ? ? (0x8f) reserved ? ? ? ? ? ? ? ? (0x8e) reserved ? ? ? ? ? ? ? ? (0x8d) reserved ? ? ? ? ? ? ? ? (0x8c) reserved ? ? ? ? ? ? ? ? (0x8b) reserved ? ? ? ? ? ? ? ? (0x8a) reserved ? ? ? ? ? ? ? ? (0x89) ocr1ah timer/counter1 ? output compare register a high byte 101 (0x88) ocr1al timer/counter1 ? output compare register a low byte 101 (0x87) reserved ? ? ? ? ? ? ? ? (0x86) reserved ? ? ? ? ? ? ? ? (0x85) tcnt1h timer/counter1 ? counter register high byte 101 (0x84) tcnt1l timer/counter1 ? counter register low byte 101 (0x83) reserved ? ? ? ? ? ? ? ? (0x82) reserved ? ? ? ? ? ? ? ? (0x81) tccr1b ? ? ? ? ctc1 cs12 cs11 cs10 100 (0x80) reserved ? ? ? ? ? ? ? ? (0x7f) reserved ? ? ? ? ? ? ? ? (0x7e) didr0 ? ? ? ? vadc3d vadc2d vadc1d vadc0d 120 address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page
238 2548f?avr?03/2013 atmega406 (0x7d) reserved ? ? ? ? ? ? ? ? (0x7c) vadmux ? ? ? ? vadmux3 vadmux2 vadmux1 vadmux0 118 (0x7b) reserved ? ? ? ? ? ? ? ? (0x7a) vadcsr ? ? ? ? vaden vadsc vadccif vadccie 118 (0x79) vadch ? ? ? ? vadc data register high byte 119 (0x78) vadcl vadc data register low byte 119 (0x77) reserved ? ? ? ? ? ? ? ? (0x76) reserved ? ? ? ? ? ? ? ? (0x75) reserved ? ? ? ? ? ? ? ? (0x74) reserved ? ? ? ? ? ? ? ? (0x73) reserved ? ? ? ? ? ? ? ? (0x72) reserved ? ? ? ? ? ? ? ? (0x71) reserved ? ? ? ? ? ? ? ? (0x70) reserved ? ? ? ? ? ? ? ? (0x6f) timsk1 ? ? ? ? ? ?ocie1atoie1 102 (0x6e) timsk0 ? ? ? ? ? ocie0b ocie0a toie0 93 (0x6d) reserved ? ? ? ? ? ? ? ? (0x6c) pcmsk1 pcint[15:8] 59 (0x6b) pcmsk0 pcint[7:0] 59 (0x6a) reserved ? ? ? ? ? ? ? ? (0x69) eicra isc31 isc30 isc21 isc20 isc11 isc10 isc01 isc00 56 (0x68) pcicr ? ? ? ? ? ?pcie1pcie0 58 (0x67) reserved ? ? ? ? ? ? ? ? (0x66) fosccal fast oscillat or calibration register 29 (0x65) reserved ? ? ? ? ? ? ? ? (0x64) prr0 ? ? ? ? prtwi prtim1 prtim0 prvadc 36 (0x63) reserved ? ? ? ? ? ? ? ? (0x62) wutcsr wutif wutie wutcf wutr wute wutp2 wutp1 wutp0 49 (0x61) reserved ? ? ? ? ? ? ? ? (0x60) wdtcsr wdif wdie wdp3 wdce wde wdp2 wdp1 wdp0 47 0x3f (0x5f) sreg i t h s v n z c 10 0x3e (0x5e) sph sp15 sp14 sp13 sp12 sp11 sp10 sp9 sp8 12 0x3d (0x5d) spl sp7 sp6 sp5 sp4 sp3 sp2 sp1 sp0 12 0x3c (0x5c) reserved ? ? ? ? ? ? ? ? 0x3b (0x5b) reserved ? ? ? ? ? ? ? ? 0x3a (0x5a) reserved ? ? ? ? ? ? ? ? 0x39 (0x59) reserved ? ? ? ? ? ? ? ? 0x38 (0x58) reserved ? ? ? ? ? ? ? ? 0x37 (0x57) spmcsr spmie rwwsb sigrd rwwsre blbset pgwrt pgers spmen 183 0x36 (0x56) reserved ? ? ? ? ? ? ? ? 0x35 (0x55) mcucr jtd ? ?pud ? ? ivsel ivce 55/73/176 0x34 (0x54) mcusr ? ? ? jtrf wdrf bodrf extrf porf 46 0x33 (0x53) smcr ? ? ? ? sm2 sm1 sm0 se 31 0x32 (0x52) reserved ? ? ? ? ? ? ? ? 0x31 (0x51) ocdr on-chip debug register 176 0x30 (0x50) reserved ? ? ? ? ? ? ? ? 0x2f (0x4f) reserved ? ? ? ? ? ? ? ? 0x2e (0x4e) reserved ? ? ? ? ? ? ? ? 0x2d (0x4d) reserved ? ? ? ? ? ? ? ? 0x2c (0x4c) reserved ? ? ? ? ? ? ? ? 0x2b (0x4b) gpior2 general purpose i/o register 2 24 0x2a (0x4a) gpior1 general purpose i/o register 1 24 0x29 (0x49) reserved ? ? ? ? ? ? ? ? 0x28 (0x48) ocr0b timer/counter0 output compare register b 92 0x27 (0x47) ocr0a timer/counter0 output compare register a 92 0x26 (0x46) tcnt0 timer/counter0 (8 bit) 92 0x25 (0x45) tccr0b foc0a foc0b ? ? wgm02 cs02 cs01 cs00 91 0x24 (0x44) tccr0a com0a1 com0a0 com0b1 com0b0 ? ?wgm01wgm00 88 0x23 (0x43) gtccr tsm ? ? ? ? ? ? psrsync 105 0x22 (0x42) eearh ? ? ? ? ? ? ? high byte 19 0x21 (0x41) eearl eeprom address register low byte 19 0x20 (0x40) eedr eeprom data register 19 0x1f (0x3f) eecr ? ? eepm1 eepm0 eerie eempe eepe eere 19 0x1e (0x3e) gpior0 general purpose i/o register 0 24 0x1d (0x3d) eimsk ? ? ? ? int3 int2 int1 int0 57 0x1c (0x3c) eifr ? ? ? ? intf3 intf2 intf1 intf0 57 address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page
239 2548f?avr?03/2013 atmega406 notes: 1. for compatibility with future devices, reserved bits shou ld be written to zero if accesse d. reserved i/o memory address es should never be written. 2. i/o registers within the address range $00 - $1f are directly bit-accessible using th e sbi and cbi instructions. in these reg - isters, the value of single bits can be che cked by using the sbis and sbic instructions. 3. some of the status flags are cleared by writing a logical one to them. note that the cbi and sbi instructions will operate on all bits in the i/o register, writing a one back into any flag r ead as set, thus clearing the flag. the cbi and sbi instruction s work with registers 0x00 to 0x1f only. 4. when using the i/o specific commands in and out, the i/o addresses $00 - $3f must be used. when addressing i/o reg- isters as data space using ld and st instructions, $20 mu st be added to these addresse s. the atmega406 is a complex microcontroller with more peripheral units than can be support ed within the 64 location reserved in opcode for the in and out instructions. for the extended i/o space from $60 - $ff in sram, only the st/sts/std and ld/lds/ldd instructions can be used. 0x1b (0x3b) pcifr ? ? ? ? ? ?pcif1pcif0 0x1a (0x3a) reserved ? ? ? ? ? ? ? ? 0x19 (0x39) reserved ? ? ? ? ? ? ? ? 0x18 (0x38) reserved ? ? ? ? ? ? ? ? 0x17 (0x37) reserved ? ? ? ? ? ? ? ? 0x16 (0x36) tifr1 ? ? ? ? ? ?ocf1atov1 102 0x15 (0x35) tifr0 ? ? ? ? ?ocf0bocf0atov0 94 0x14 (0x34) reserved ? ? ? ? ? ? ? ? 0x13 (0x33) reserved ? ? ? ? ? ? ? ? 0x12 (0x32) reserved ? ? ? ? ? ? ? ? 0x11 (0x31) reserved ? ? ? ? ? ? ? ? 0x10 (0x30) reserved ? ? ? ? ? ? ? ? 0x0f (0x2f) reserved ? ? ? ? ? ? ? ? 0x0e (0x2e) reserved ? ? ? ? ? ? ? ? 0x0d (0x2d) reserved ? ? ? ? ? ? ? ? 0x0c (0x2c) reserved ? ? ? ? ? ? ? ? 0x0b (0x2b) portd ? ? ? ? ? ? portd1 portd0 74 0x0a (0x2a) ddrd ? ? ? ? ? ? ddd1 ddd0 74 0x09 (0x29) pind ? ? ? ? ? ? pind1 pind0 74 0x08 (0x28) portc ? ? ? ? ? ? ?portc0 76 0x07 (0x27) reserved ? ? ? ? ? ? ? ? 0x06 (0x26) reserved ? ? ? ? ? ? ? ? 0x05 (0x25) portb portb7 portb6 portb5 portb4 portb3 portb2 portb1 portb0 74 0x04 (0x24) ddrb ddb7 ddb6 ddb5 ddb4 ddb3 ddb2 ddb1 ddb0 74 0x03 (0x23) pinb pinb7 pinb6 pinb5 pinb4 pinb3 pinb2 pinb1 pinb0 74 0x02 (0x22) porta porta7 porta6 porta5 porta4 portb3 porta2 porta1 porta0 73 0x01 (0x21) ddra dda7 dda6 dda5 dda4 dda3 dda2 dda1 dda0 73 0x00 (0x20) pina pina7 pina6 pina5 pina4 pina3 pina2 pina1 pina0 73 address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page
240 2548f?avr?03/2013 atmega406 33. instruction set summary mnemonics operands description operation flags #clocks arithmetic and logic instructions add rd, rr add two registers rd ? rd + rr z,c,n,v,h 1 adc rd, rr add with carry two registers rd ? rd + rr + c z,c,n,v,h 1 adiw rdl,k add immediate to word rdh:rdl ? rdh:rdl + k z,c,n,v,s 2 sub rd, rr subtract two registers rd ? rd - rr z,c,n,v,h 1 subi rd, k subtract constant from register rd ? rd - k z,c,n,v,h 1 sbc rd, rr subtract with carry two registers rd ? rd - rr - c z,c,n,v,h 1 sbci rd, k subtract with carry constant from reg. rd ? rd - k - c z,c,n,v,h 1 sbiw rdl,k subtract immediate from word rdh:rdl ? rdh:rdl - k z,c,n,v,s 2 and rd, rr logical and registers rd ?? rd ? rr z,n,v 1 andi rd, k logical and register and constant rd ? rd ?? k z,n,v 1 or rd, rr logical or registers rd ? rd v rr z,n,v 1 ori rd, k logical or register and constant rd ?? rd v k z,n,v 1 eor rd, rr exclusive or registers rd ? rd ? rr z,n,v 1 com rd one?s complement rd ? 0xff ? rd z,c,n,v 1 neg rd two?s complement rd ? 0x00 ? rd z,c,n,v,h 1 sbr rd,k set bit(s) in register rd ? rd v k z,n,v 1 cbr rd,k clear bit(s) in register rd ? rd ? (0xff - k) z,n,v 1 inc rd increment rd ? rd + 1 z,n,v 1 dec rd decrement rd ? rd ? 1 z,n,v 1 tst rd test for zero or minus rd ? rd ? rd z,n,v 1 clr rd clear register rd ? rd ? rd z,n,v 1 ser rd set register rd ? 0xff none 1 mul rd, rr multiply unsigned r1:r0 ? rd x rr z,c 2 muls rd, rr multiply signed r1:r0 ? rd x rr z,c 2 mulsu rd, rr multiply signed with unsigned r1:r0 ? rd x rr z,c 2 fmul rd, rr fractional multiply unsigned r1:r0 ? (rd x rr) << 1 z,c 2 fmuls rd, rr fractional multiply signed r1:r0 ? (rd x rr) << 1 z,c 2 fmulsu rd, rr fractional multiply signed with unsigned r1:r0 ? (rd x rr) << 1 z,c 2 branch instructions rjmp k relative jump pc ?? pc + k + 1 none 2 ijmp indirect jump to (z) pc ? z none 2 jmp k direct jump pc ?? knone3 rcall k relative subroutine call pc ? pc + k + 1 none 3 icall indirect call to (z) pc ? znone3 call k direct subroutine call pc ? knone4 ret subroutine return pc ? stack none 4 reti interrupt return pc ? stack i 4 cpse rd,rr compare, skip if equal if (rd = rr) pc ?? pc + 2 or 3 none 1/2/3 cp rd,rr compare rd ? rr z, n,v,c,h 1 cpc rd,rr compare with carry rd ? rr ? c z, n,v,c,h 1 cpi rd,k compare register with immediate rd ? k z, n,v,c,h 1 sbrc rr, b skip if bit in register cleared if (rr(b)=0) pc ? pc + 2 or 3 none 1/2/3 sbrs rr, b skip if bit in register is set if (rr(b)=1) pc ? pc + 2 or 3 none 1/2/3 sbic p, b skip if bit in i/o register cleared if (p(b)=0) pc ? pc + 2 or 3 none 1/2/3 sbis p, b skip if bit in i/o register is set if (p(b)=1) pc ? pc + 2 or 3 none 1/2/3 brbs s, k branch if status flag set if (sreg(s) = 1) then pc ? pc+k + 1 none 1/2 brbc s, k branch if status flag cleared if (sreg(s) = 0) then pc ? pc+k + 1 none 1/2 breq k branch if equal if (z = 1) then pc ? pc + k + 1 none 1/2 brne k branch if not equal if (z = 0) then pc ? pc + k + 1 none 1/2 brcs k branch if carry set if (c = 1) then pc ? pc + k + 1 none 1/2 brcc k branch if carry cleared if (c = 0) then pc ? pc + k + 1 none 1/2 brsh k branch if same or higher if (c = 0) then pc ? pc + k + 1 none 1/2 brlo k branch if lower if (c = 1) then pc ? pc + k + 1 none 1/2 brmi k branch if minus if (n = 1) then pc ? pc + k + 1 none 1/2 brpl k branch if plus if (n = 0) then pc ? pc + k + 1 none 1/2 brge k branch if greater or equal, signed if (n ? v= 0) then pc ? pc + k + 1 none 1/2 brlt k branch if less than zero, signed if (n ? v= 1) then pc ? pc + k + 1 none 1/2 brhs k branch if half carry flag set if (h = 1) then pc ? pc + k + 1 none 1/2 brhc k branch if half carry flag cleared if (h = 0) then pc ? pc + k + 1 none 1/2 brts k branch if t flag set if (t = 1) then pc ? pc + k + 1 none 1/2 brtc k branch if t flag cleared if (t = 0) then pc ? pc + k + 1 none 1/2 brvs k branch if overflow flag is set if (v = 1) then pc ? pc + k + 1 none 1/2 brvc k branch if overflow flag is cleared if (v = 0) then pc ? pc + k + 1 none 1/2
241 2548f?avr?03/2013 atmega406 brie k branch if interrupt enabled if ( i = 1) then pc ? pc + k + 1 none 1/2 brid k branch if interrupt disabled if ( i = 0) then pc ? pc + k + 1 none 1/2 bit and bit-test instructions sbi p,b set bit in i/o register i/o(p,b) ? 1none2 cbi p,b clear bit in i/o register i/o(p,b) ? 0none2 lsl rd logical shift left rd(n+1) ? rd(n), rd(0) ? 0 z,c,n,v 1 lsr rd logical shift right rd(n) ? rd(n+1), rd(7) ? 0 z,c,n,v 1 rol rd rotate left through carry rd(0) ? c,rd(n+1) ? rd(n),c ? rd(7) z,c,n,v 1 ror rd rotate right through carry rd(7) ? c,rd(n) ? rd(n+1),c ? rd(0) z,c,n,v 1 asr rd arithmetic shift right rd(n) ? rd(n+1), n=0..6 z,c,n,v 1 swap rd swap nibbles rd(3..0) ? rd(7..4),rd(7..4) ? rd(3..0) none 1 bset s flag set sreg(s) ? 1 sreg(s) 1 bclr s flag clear sreg(s) ? 0 sreg(s) 1 bst rr, b bit store from register to t t ? rr(b) t 1 bld rd, b bit load from t to register rd(b) ? tnone1 sec set carry c ? 1c1 clc clear carry c ? 0 c 1 sen set negative flag n ? 1n1 cln clear negative flag n ? 0 n 1 sez set zero flag z ? 1z1 clz clear zero flag z ? 0 z 1 sei global interrupt enable i ? 1i1 cli global interrupt disable i ?? 0 i 1 ses set signed test flag s ? 1s1 cls clear signed test flag s ? 0 s 1 sev set twos complement overflow. v ? 1v1 clv clear twos complement overflow v ? 0 v 1 set set t in sreg t ? 1t1 clt clear t in sreg t ? 0 t 1 seh set half carry flag in sreg h ? 1h1 clh clear half carry flag in sreg h ? 0 h 1 data transfer instructions mov rd, rr move between registers rd ? rr none 1 movw rd, rr copy register word rd+1:rd ? rr+1:rr none 1 ldi rd, k load immediate rd ? knone1 ld rd, x load indirect rd ? (x) none 2 ld rd, x+ load indirect and post-inc. rd ? (x), x ? x + 1 none 2 ld rd, - x load indirect and pre-dec. x ? x - 1, rd ? (x) none 2 ld rd, y load indirect rd ? (y) none 2 ld rd, y+ load indirect and post-inc. rd ? (y), y ? y + 1 none 2 ld rd, - y load indirect and pre-dec. y ? y - 1, rd ? (y) none 2 ldd rd,y+q load indirect with displacement rd ? (y + q) none 2 ld rd, z load indirect rd ? (z) none 2 ld rd, z+ load indirect and post-inc. rd ? (z), z ? z+1 none 2 ld rd, -z load indirect and pre-dec. z ? z - 1, rd ? (z) none 2 ldd rd, z+q load indirect with displacement rd ? (z + q) none 2 lds rd, k load direct from sram rd ? (k) none 2 st x, rr store indirect (x) ?? rr none 2 st x+, rr store indirect and post-inc. (x) ?? rr, x ? x + 1 none 2 st - x, rr store indirect and pre-dec. x ? x - 1, (x) ? rr none 2 st y, rr store indirect (y) ? rr none 2 st y+, rr store indirect and post-inc. (y) ? rr, y ? y + 1 none 2 st - y, rr store indirect and pre-dec. y ? y - 1, (y) ? rr none 2 std y+q,rr store indirect with displacement (y + q) ? rr none 2 st z, rr store indirect (z) ? rr none 2 st z+, rr store indirect and post-inc. (z) ? rr, z ? z + 1 none 2 st -z, rr store indirect and pre-dec. z ? z - 1, (z) ? rr none 2 std z+q,rr store indirect with displacement (z + q) ? rr none 2 sts k, rr store direct to sram (k) ? rr none 2 lpm load program memory r0 ? (z) none 3 lpm rd, z load program memory rd ? (z) none 3 lpm rd, z+ load program memory and post-inc rd ? (z), z ? z+1 none 3 spm store program memory (z) ? r1:r0 none - in rd, p in port rd ? pnone1 33. instruction set su mmary (continued) mnemonics operands description operation flags #clocks
242 2548f?avr?03/2013 atmega406 out p, rr out port p ? rr none 1 push rr push register on stack stack ? rr none 2 pop rd pop register from stack rd ? stack none 2 mcu control instructions nop no operation none 1 sleep sleep (see specific descr. for sleep function) none 1 wdr watchdog reset (see specific descr. for wdr/timer) none 1 break break for on-chip debug only none n/a 33. instruction set su mmary (continued) mnemonics operands description operation flags #clocks
243 2548f?avr?03/2013 atmega406 34. ordering information notes: 1. this device can also be supplied in wafer form. please c ontact your local atmel sales office for detailed ordering info rmation and minimum quantities. 2. pb-free packaging alternative, complies to the european directive for restriction of hazardous substances (rohs direc- tive). also halide free and fully green. speed (mhz) power supply ordering code package (1) operation range 1 4.0 - 25v atmega406-1aau (2) 48aa industrial (-30 ? c to 85 ? c) package type 48aa 48-lead, 7 x 7 x 1.44 mm body, 0.5 mm lead pitc h, low profile plastic quad flat package (lqfp)
244 2548f?avr?03/2013 atmega406 35. packaging information 35.1 48aa 2 3 25 orch a rd p a rkw a y sa n jo s e, ca 951 3 1 title drawing no. r rev. 4 8 aa, 4 8 -le a d, 7 x 7 mm body s ize, 1.4 mm body thickne ss , 0.5 mm le a d pitch, low profile pl as tic q ua d fl a t p a ck a ge (lqfp) d 4 8 aa 2010-10-19 pin 1 identifier 0~7 pin 1 l c a1 a2 a d1 d e e1 e b common dimen s ion s (unit of me asu re = mm) s ymbol min nom max note note s : 1. thi s p a ck a ge conform s to jedec reference m s -026, v a ri a tion bbc. 2. dimen s ion s d1 a nd e1 do not incl u de mold protr us ion. allow ab le protr us ion i s 0.25 mm per s ide. dimen s ion s d1 a nd e1 a re m a xim u m pl as tic b ody s ize dimen s ion s incl u ding mold mi s m a tch. 3 . le a d copl a n a rity i s 0.0 8 mm m a xim u m. a ? ? 1.60 a1 0.05 ? 0.15 a2 1. 3 5 1.40 1.45 d 8 .75 9.00 9.25 d1 6.90 7.00 7.10 note 2 e 8 .75 9.00 9.25 e1 6.90 7.00 7.10 note 2 b 0.17 ? 0.27 c 0.09 ? 0.20 l 0.45 ? 0.75 e 0.50 typ
245 2548f?avr?03/2013 atmega406 36. errata 36.1 rev. f ? voltage-adc common mode offset ? voltage reference spike 1. voltage-adc common mode offset the cell conversion will have an offset-error depending on the comm on mode (cm) level. this means that the error of a cell is depending on the voltage of the lower cells. the cm offset is calibrated aw ay in atmel production when the ce lls are balanced. when the cells get un-balanced the cm depen ding offset will reappear: a. cell 1 defines its own cm level, and will never be affected by the cm dependent offset. b. the cm level for cell 2 will change if ce ll 1 voltage deviates from cell 2 voltage. c. the cm level for cell 3 will change if cell 1 and/or cell 2 volta ge deviates from the voltage at cell 3. the worst-case error is when cell 1 and 2 are balanced while cell 3 voltage deviates from the voltage at cell 1 and 2. d. the cm level for cell 4 will change if cell 1, cell 2 and/or cell 3 dev iate from the volt- age at cell 4. the worst-case error is when cell 1, cell 2 and cell 3 are balanced while cell 4 voltage deviates from the voltage at cell 1, 2 and 3. figure 36-1 on page 246 , shows the error of cell2, cell3 and cell4 with 5% and 10% unbal- anced cells.
246 2548f?avr?03/2013 atmega406 figure 36-1. cm offset with unbalanced cells. problem fix/workaround avoid getting unbalanced cells by usi ng the internal cell balancing fets. 2. voltage reference spike the voltage reference, vref, will spike each time the internal te mperature sensor is enabled. the temperature sensor is enabled w hen the vtemp is selected in the vadmux register and the v-adc is enabled by the vaden bit. the spike will be approximately 50 mv and lasts for about 5ms, and it will affect any ongoing current accumulation in the cc -adc, as well as v-adc conver sions in the period of the spike. figure 36-2 on page 247 illustrates the volt age reference spike.
247 2548f?avr?03/2013 atmega406 figure 36-2. voltage reference spike problem workaround: to get correct temperature measurement, t he vadsc bit should not be written until the spike has settled (external decoupling capacitor of 1 ? f). vref time voltage t ~< 5ms v~50mv 1.1 v vaden vadmux3:0 xxx vtemp
248 2548f?avr?03/2013 atmega406 36.2 rev. e ? voltage adc not functional below 0 c ? voltage-adc common mode offset ? voltage reference spike 1. voltage-adc failing at low temperatures voltage adc not functional below 0c. the vo ltage adc has a very large error below 0c, and can not be used problem fix/workaround do not use this revision below 0 celsius. 2. voltage-adc common mode offset the cell conversion will have an offset-error depending on the comm on mode (cm) level. this means that the error of a cell is depending on the voltage of the lower cells. the cm offset is calibrated aw ay in atmel production when the ce lls are balanced. when the cells get un-balanced the cm depen ding offset will reappear: a. cell 1 defines its own cm level, and will never be affected by the cm dependent offset. b. the cm level for cell 2 will change if ce ll 1 voltage deviates from cell 2 voltage. c. the cm level for cell 3 will change if cell 1 and/or cell 2 volta ge deviates from the voltage at cell 3. the worst-case error is when cell 1 and 2 are balanced while cell 3 voltage deviates from the voltage at cell 1 and 2. d. the cm level for cell 4 will change if cell 1, cell 2 and/or cell 3 dev iate from the volt- age at cell 4. the worst-case error is when cell 1, cell 2 and cell 3 are balanced while cell 4 voltage deviates from the voltage at cell 1, 2 and 3. figure 36-1 on page 246 , shows the error of cell2, cell3 and cell4 with 5% and 10% unbal- anced cells.
249 2548f?avr?03/2013 atmega406 figure 36-3. cm offset with unbalanced cells. problem fix/workaround avoid getting unbalanced cells by usi ng the internal cell balancing fets. 3. voltage reference spike the voltage reference, vref, will spike each time a temperature measurement is started with the voltage-adc. problem fix/workaround an accurate temperature measurement could be obtained by doing 10 temperature conver- sions immediately after each other. the firs t 9 results would be inaccurate, but the 10th conversion will be correct. figure 36-4 on page 250 illustrates the spike on the volt age reference when doing 10 tem- perature conversions in a row (external decoupling capacitor of 1 ? f).
250 2548f?avr?03/2013 atmega406 figure 36-4. voltage reference spike if the cc-adc is doing current accumulation while the v-adc is doing temperature mea- surement, both the instantaneous and the accumu lated conversion results will be affected. the spike on vref will be visible on 1 accumu lated current (cadac3? 0) and 2 instanta- neous current (cadic1?0) conversion results. 36.3 rev. d ? voltage adc not functional below 0 c ? voltage-adc common mode offset ? voltage reference spike ? voltage regulator start-up sequence ? v ref influenced by mcu state ? eeprom read from ap plication code does not wo rk in lock bit mode 3 1. voltage-adc failing at low temperatures voltage adc not functional below 0c. the vo ltage adc has a very large error below 0c, and can not be used problem fix/workaround 1. voltage-adc common mode offset the cell conversion will have an offset-error depending on the comm on mode (cm) level. this means that the error of a cell is depending on the voltage of the lower cells. the cm offset is calibrated aw ay in atmel production when the ce lls are balanced. when the cells get un-balanced the cm depen ding offset will reappear: vref time voltage t ~< 5ms v~50mv 1.1 v vadsc (10 vtemp conversion in a row) vadmux3:0 xxx vtemp
251 2548f?avr?03/2013 atmega406 a. cell 1 defines its own cm level, and will never be affected by the cm dependent offset. b. the cm level for cell 2 will change if ce ll 1 voltage deviates from cell 2 voltage. c. the cm level for cell 3 will change if cell 1 and/or cell 2 volta ge deviates from the voltage at cell 3. the worst-case error is when cell 1 and 2 are balanced while cell 3 voltage deviates from the voltage at cell 1 and 2. d. the cm level for cell 4 will change if cell 1, cell 2 and/or cell 3 dev iate from the volt- age at cell 4. the worst-case error is when cell 1, cell 2 and cell 3 are balanced while cell 4 voltage deviates from the voltage at cell 1, 2 and 3. figure 36-1 on page 246 , shows the error of cell2, cell3 and cell4 with 5% and 10% unbal- anced cells. figure 36-5. cm offset with unbalanced cells. problem fix/workaround avoid getting unbalanced cells by usi ng the internal cell balancing fets.
252 2548f?avr?03/2013 atmega406 3. voltage reference spike the voltage reference, vref, will spike each time a temperature measurement is started with the voltage-adc. problem fix/workaround an accurate temperature measurement could be obtained by doing 10 temperature conver- sions immediately after each other. the firs t 9 results would be inaccurate, but the 10th conversion will be correct. figure 36-6 illustrates the spike on the voltage refe rence when doing 10 temperature con- versions in a row (external decoupling capacitor of 1 ? f). figure 36-6. voltage reference spike if the cc-adc is doing current accumulation while the v-adc is doing temperature mea- surement, both the instantaneous and the accumu lated conversion results will be affected. the spike on vref will be visible on 1 accumu lated current (cadac3? 0) and 2 instanta- neous current (cadic1?0) conversion results. vref time voltage t ~< 5ms v~50mv 1.1 v vadsc (10 vtemp conversion in a row) vadmux3:0 xxx vtemp
253 2548f?avr?03/2013 atmega406 4. voltage regulator start-up sequence when powering up atmega406 some precautions are necessary to ensure proper start-up of the voltage regulator. problem fix/workaround the three steps below are needed to ensure pr oper start-up of the voltage regulator. a. do not connect a capacitor larger than 100 nf on the vfet pin. this is to ensure fast rise time on the vfet pin when a supply voltage is connected. b. during assembly, always connect cell1 first, then cell2 and so on until the top cell is connected to pvt. if the cell voltages are about 2 volts or larger, the voltage regula- tor will normally start up properly in po wer-off mode (vreg appr. 2.8 volts). c. after all cells have been assembled as described in step 2, a charger source must be connected at the batt+ terminal to initialize the chip, see section 8.3 ?power-on reset and charger connect? on page 38 in the datasheet. if the voltage regulator started up in power-off during assembly of the cells, the chip will ini- tialize when the charger source makes the voltage at the batt pin exceed 7 - 8 volts. if the voltage regulator did not start up properly, the charger source has one additional requirement to ensure proper start up and initia lization. in this case the charger source must ensure that the voltage at the vfet pin increases quickly at least 3 volts above the voltage at the pvt pin, and that the voltage at the batt pin exceeds 7 - 8 volts. this will start up and initialize the chip directly. 5. v ref influenced by mcu state the reference voltage at the v ref pin depends on the following conditions of the device: a. charger over-current and/or discharge over -current protection active but short-cir- cuit inactive. this will increase v ref voltage with typical 1 mv compared to a condition were all current protections are disabled. b. short-circuit protection active. short-ci rcuit measurements are activated when scd in bpcr is zero (default) and dfe in fet co ntrol and status register (fcsr) is set. this will increase v ref voltage with typical 8 mv compared to a condition with short- circuit measurements inactive. c. v-adc conversion of the internal vt emp voltage. this will increase v ref voltage with typical 15 mv compared to a condition with short-circuit measurements inactive. problem fix/work around to ensure the highest accuracy, set the bandgap calibration register (bgcc) to get 1.100 v at v ref after the chip is configur ed with the actual battery pr otection settings and the dis- charge fet is enabled. 6. eeprom read from applic ation code does not work in lock bit mode 3 when the memory lock bits lb2 and lb1 are programmed to mode 3, eeprom read does not work from the application code. problem fix/work around do not set lock bit protection mode 3 when the application code needs to read from eeprom.
254 2548f?avr?03/2013 atmega406 37. datasheet revision history 37.1 rev 2548f - 03/13 37.2 rev 2548e - 07/06 1. updated heading titles of ?ppi/nni? and ?pi/ni? on page 6 . 2. updated note 10 in table 27-5 on page 189 3. updated section 30.2 on page 225 . 1. updated ?pin configurations? on page 2 . 2. updated ?adc noise reduction mode? on page 32 . 3. updated ?power-save mode? on page 32 . 4. updated ?power-down mode? on page 33 . 5 updated ?power-off mode? on page 33 . 6. updated ?power reduction register? on page 36 . 7. added ?voltage adc? on page 37 and ?coloumb counter? on page 38 . 8. updated ?reset sources? on page 39 . 9. updated ?power-on reset and charger connect? on page 40 . 10. updated ?external reset? on page 41 . 11. v cc replaced by vreg in ?brown-out detection? on page 42 . 12. updated ?alternate port functions? on page 66 . 13. updated ?internal clock source? on page 103 . 14. updated ?external clock source? on page 103 . 15. updated features in ?coulomb counter - dedicated fuel gauging sigma-delta adc? on page 106 . 16. updated operation in section 18. ?coulomb counter - dedicated fuel gauging sigma-delta adc? on page 106 . 17. updated features in ?voltage regulator? on page 114 . 18. updated operation in ?voltage regulator? on page 114 . 19. updated bit description in ?vadcl and vadch ? the v-adc data register? on page 119 . 20. updated ?writing to bandgap calibration registers? on page 122 . 21. updated text in ?register description for fet control? on page 134 . 22. added ?mcucr ? mcu control register? on page 176 . 23 updated ?operating circuit? on page 223 24. updated ?electrical characteristics? on page 225 . 25. added ?typical characteristics ? preliminary? on page 232 . 26 updated ?register summary? on page 236 . 27. updated ?errata? on page 245 . 28. updated table 9-2 on page 48 , table 27-5 on page 189 . 29. updated figure 8-1 on page 35 , figure 9-5 on page 42 , figure 17-2 on page 104 , figure 18-2 on page 107 , figure 18-3 on page 108 , figure 19-1 on page 114 , figure 29-1 on page 223 . 30. updated register adresses.
255 2548f?avr?03/2013 atmega406 37.3 rev 2548d - 06/05 37.4 rev 2548c - 05/05 37.5 rev 2548b - 04/05 1. updated section 36. ?errata? on page 245 . 1. updated section 36. ?errata? on page 245 . 1. typos updated, bit ?psrasy? removed, cs12 :0 renamed cs1[2:0]. 2. removed ?bgen? bit in bgccr regist er. the bandgap voltage reference is always enabled in atmega406 revision e. 3. updated figure 2-1 on page 3 , figure 6-1 on page 25 , figure 24-9 on page 137 , fig- ure 21-1 on page 120 . 4. updated table 7-2 on page 33 , table 7-3 on page 34 , table 8-1 on page 38 , table 26-5 on page 181 , figure 27-1 on page 188 . 5. updated section 12.3.2 ?alternate func tions of port a? on page 66 and section 21. ?battery protection? on page 118 description. 6. updated registers ?external interrupt flag register ? eifr? on page 55 and ?timer/counter control register b ? tccr0b? on page 89 . 7. updated section 17.1 ?features? on page 103 and section 17.2 ?operation? on page 103 . updated section 19.1 ?features? on page 111 . updated section 20.2 ?register description for voltage reference and temperature sensor? on page 116 . 8. updated section 29. ?electrical characteristics? on page 211 . 9. updated section 35. ?errata? on page 225 .
256 2548f?avr?03/2013 atmega406
i 2548f?avr?03/2013 atmega406 table of contents features .............. ................ ................ ............... .............. .............. ............ 1 1 pin configurations ... ................ ................ ................. ................ ............... 2 1.1 disclaimer ................................................................................................................ .2 2 overview ................ .............. .............. ............... .............. .............. ............ 3 2.1 block diagram ..........................................................................................................3 2.2 pin descriptions .......................................................................................................5 3 resources .............. .............. .............. ............... .............. .............. ............ 7 4 about code examples ........ .............. ............... .............. .............. ............ 7 5 avr cpu core ................. ................ ................. .............. .............. ............ 8 5.1 introduction .............................................................................................................. .8 5.2 architectural overview .............................................................................................8 5.3 alu ? arithmetic logic unit .....................................................................................9 5.4 status register .......................................................................................................10 5.5 general purpose register file ...............................................................................11 5.6 stack pointer ..........................................................................................................12 5.7 instruction execution timing ..................................................................................13 5.8 reset and interrupt handling .................................................................................14 6 avr memories .......... ................ ................ ................. ................ ............. 16 6.1 in-system reprogrammable flash program memory ............................................16 6.2 sram data memory ..............................................................................................17 6.3 eeprom data memory ..... ................ ................ ................. ............ ............. ..........18 6.4 i/o memory .............................................................................................................24 7 system clock and clock opti ons ........... ................. ................ ............. 25 7.1 clock systems and their distribution ...... ................................................................25 7.2 clock sources ........................................................................................................26 7.3 calibrated fast rc oscillator .................................................................................26 7.4 32 khz crystal oscillator ........................................................................................27 7.5 slow rc oscillator .................................................................................................27 7.6 ultra low power rc oscillator ...............................................................................27 7.7 cpu, i/o, flash, and voltage adc clock ...............................................................27 7.8 coulomb counter adc and wake-up time r clock ................................................28 7.9 watchdog timer and battery protection clock .......................................................28
ii 2548f?avr?03/2013 atmega406 7.10 run-time clock source select ............................................................................28 7.11 register description ... ..........................................................................................29 8 power management and sleep modes ........... .............. .............. .......... 31 8.1 idle mode ................................................................................................................3 2 8.2 adc noise reduction mode .................. ................................................................32 8.3 power-save mode ..................................................................................................32 8.4 power-down mode .................................................................................................33 8.5 power-off mode ......................................................................................................33 8.6 power reduction register ......................................................................................36 8.7 minimizing power consumption .............................................................................37 9 system control and reset .... .............. .............. .............. .............. ........ 39 9.1 resetting the avr ..................................................................................................39 9.2 reset sources ........................................................................................................39 9.3 watchdog timer .....................................................................................................43 9.4 register description ...............................................................................................46 10 wake-up timer ........... ................ ................. ................ ................. .......... 49 10.1 overview ..............................................................................................................49 10.2 register description ... ..........................................................................................49 11 interrupts ............... .............. .............. ............... .............. .............. .......... 51 11.1 interrupt vectors in atmega406 ..........................................................................51 11.2 moving interrupts betwee n application and boot space .....................................54 11.3 register description ... ..........................................................................................55 12 external interrupts .......... ................ ................. .............. .............. .......... 56 12.1 overview ..............................................................................................................56 12.2 register description ... ..........................................................................................56 13 low voltage i/o-ports ......... .............. ............... .............. .............. .......... 60 13.1 introduction ...........................................................................................................60 13.2 low voltage ports as general digital i/o .............................................................61 13.3 alternate port functions .......................................................................................66 13.4 register description ... ..........................................................................................73 14 high voltage i/o ports ........ .............. ............... .............. .............. .......... 75 14.1 high voltage ports as general digital outputs ....................................................75 14.2 configuring the pin ...............................................................................................76 14.3 register description for high voltage output ports .............................................76
iii 2548f?avr?03/2013 atmega406 15 8-bit timer/counter0 with pw m .............. ................. ................ ............. 77 15.1 overview ..............................................................................................................77 15.2 timer/counter clock sources .............. ................................................................78 15.3 counter unit .........................................................................................................78 15.4 output compare unit ...........................................................................................79 15.5 compare match output un it .................................................................................81 15.6 modes of operation ..............................................................................................82 15.7 timer/counter timing diagrams .......... ................................................................86 15.8 8-bit timer/counter regi ster description .............................................................88 16 16-bit timer/counter1 ......... .............. ............... .............. .............. .......... 95 16.1 overview ..............................................................................................................95 16.2 accessing 16-bit registers ...................................................................................96 16.3 timer/counter clock sources .............. ................................................................98 16.4 counter unit .........................................................................................................99 16.5 output compare unit ...........................................................................................99 16.6 16-bit timer/counter register description .........................................................100 17 timer/counter0 and timer/counter1 pr escalers ............ .................. 103 17.1 internal clock source .........................................................................................103 17.2 prescaler reset ..................................................................................................103 17.3 external clock source ........................................................................................103 17.4 register description ... ........................................................................................105 18 coulomb counter - dedicated fue l gauging sigma-delta adc ...... 106 18.1 features .............................................................................................................106 18.2 operation ............................................................................................................107 19 voltage regulator ............. .............. .............. .............. .............. ........... 114 19.1 features .............................................................................................................114 19.2 operation ............................................................................................................114 20 voltage adc ? 10-cha nnel general purpose 12- bit sigma-delta adc .. 116 20.1 features .............................................................................................................116 20.2 operation ............................................................................................................117 20.3 register description ... ........................................................................................118 21 voltage reference and temperature sens or ........... .............. ........... 121 21.1 features .............................................................................................................121
iv 2548f?avr?03/2013 atmega406 21.2 writing to bandgap calibration registers ...........................................................122 21.3 register description for voltage refe rence and temperature sensor ..............123 22 battery protection ............. .............. .............. .............. .............. ........... 125 22.1 features .............................................................................................................125 22.2 deep under-voltage protection ..........................................................................126 22.3 discharge over-current protection .....................................................................126 22.4 charge over-current protection .........................................................................126 22.5 short-circuit protection .......................................................................................127 22.6 battery protection cpu interface .......................................................................127 22.7 register description fo r battery protection ........................................................128 23 fet control ........... ................. ................ ................. ................ ............. 133 23.1 fet driver ..........................................................................................................134 23.2 register description for fet control ..................................................................134 24 cell balancing .......... ................ ................ ................. ................ ........... 136 24.1 register description ... ........................................................................................137 25 2-wire serial interface ..... ................ .............. .............. .............. ........... 138 25.1 features .............................................................................................................138 25.2 two-wire serial interface bus definition .............................................................138 25.3 data transfer and frame format ..... ..................................................................139 25.4 multi-master bus system s, arbitration and synchronization ..............................142 25.5 overview of the twi module ..............................................................................144 25.6 twi register description ...................................................................................147 25.7 using the twi .....................................................................................................150 25.8 transmission modes ..... .....................................................................................153 25.9 multi-master systems and arbitration .................................................................167 25.10 bus connect/disconnect for two-wire se rial interface ....................................169 26 jtag interface and on-chip debug system ................... .................. 171 26.1 features .............................................................................................................171 26.2 overview ............................................................................................................171 26.3 test access port ? tap .....................................................................................171 26.4 tap controller ....................................................................................................173 26.5 using the on-chip debug system ......................................................................174 26.6 on-chip debug specific jtag instructions ........................................................175 26.7 on-chip debug related register .......................................................................176
v 2548f?avr?03/2013 atmega406 26.8 using the jtag programming capabilities ........................................................177 27 boot loader support ? read-while-w rite self-programming ......... 178 27.1 boot loader features .........................................................................................178 27.2 application and boot loader flash sections ......................................................178 27.3 read-while-write and no read-while-wri te flash sections .............................179 27.4 boot loader lock bits ........................................................................................181 27.5 entering the boot loader program .....................................................................183 27.6 addressing the flash during self-programming ................................................185 27.7 self-programming the flash ...............................................................................186 28 memory programming ........ .............. ............... .............. .............. ........ 195 28.1 program and data memory lock bits ................................................................195 28.2 fuse bits ............................................................................................................196 28.3 signature bytes ..................................................................................................198 28.4 calibration bytes ................................................................................................198 28.5 page size ...........................................................................................................198 28.6 parallel programming ........................... ..............................................................199 28.7 programming via the jtag interface .................................................................211 29 operating circuit ............. ................ .............. .............. .............. ........... 223 30 electrical characteristics ... .............. ............... .............. .............. ........ 225 30.1 absolute maximum ratings* ..............................................................................225 30.2 dc characteristics .............................................................................................225 30.3 general i/o lines characteristics .......................................................................228 30.4 2-wire serial interface characteristics ................................................................229 30.5 reset characteristics .........................................................................................230 30.6 supply current of i/o modules ...........................................................................231 31 typical characteristics ? preliminary .. ................. ................ ............. 232 31.1 pin pull-up ..........................................................................................................232 31.2 pin driver strength .............................................................................................233 31.3 internal oscillator speed ....................................................................................234 32 register summary ............ .............. .............. .............. .............. ........... 236 33 instruction set summary ... .............. ............... .............. .............. ........ 240 34 ordering information .......... .............. ............... .............. .............. ........ 243 35 packaging information ....... .............. ............... .............. .............. ........ 244
vi 2548f?avr?03/2013 atmega406 35.1 48aa ...................................................................................................................24 4 36 errata ........... ................ ................ ................. ................ .............. ........... 245 36.1 rev. f .................................................................................................................24 5 36.2 rev. e .................................................................................................................24 8 36.3 rev. d ................................................................................................................250 37 datasheet revision history .. ................ ................. ................ ............. 254 37.1 rev 2548f - 03/13 ..............................................................................................254 37.2 rev 2548e - 07/06 .............................................................................................254 37.3 rev 2548d - 06/05 .............................................................................................255 37.4 rev 2548c - 05/05 .............................................................................................255 37.5 rev 2548b - 04/05 .............................................................................................255 table of contents............... ................ ................. .............. .............. ........... i
atmel corporation 1600 technology drive san jose, ca 95110 usa tel: (+1) (408) 441-0311 fax: (+1) (408) 487-2600 www.atmel.com atmel asia limited unit 01-5 & 16, 19f bea tower, millennium city 5 418 kwun tong roa kwun tong, kowloon hong kong tel: (+852) 2245-6100 fax: (+852) 2722-1369 atmel munich gmbh business campus parkring 4 d-85748 garching b. munich germany tel: (+49) 89-31970-0 fax: (+49) 89-3194621 atmel japan g.k. 16f shin-osaki kangyo bldg 1-6-4 osaki, shinagawa-ku tokyo 141-0032 japan tel: (+81) (3) 6417-0300 fax: (+81) (3) 6417-0370 ? 2013 atmel corporation. all rights reserved. / rev.: 2548f?avr?03/2013 disclaimer: the information in this document is provided in co nnection with atmel products. no lic ense, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this document or in connection with the sale of atmel products. exc ept as set forth in the atmel terms and conditions of sales locat ed on the atmel website, atmel assumes no liability whatsoever and disclaims any express, implied or statutory warranty relating to its products including, but not li mited to, the implied warranty of merchantability, fitness for a particular purpose, or non-infringement. in no event shall atmel be liable for any d irect, indirect, consequential, punitive, special or incide ntal damages (including, without limitation, damages for loss and profits, business i nterruption, or loss of information) arising out of the us e or inability to use this document, even if at mel has been advised of the possibility of suc h damages. atmel makes no representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the ri ght to make changes to specifications and products descriptions at any time without notice. atmel does not make any commitment to update th e information contained herein. un less specifically provided oth erwise, atmel products are not suitable for, and shall not be used in, automotive applications. atmel products are not intended, authorized, or warranted for use as components in applications intend ed to support or sustain life. atmel ? , atmel logo and combinations thereof, enabling unlimited possibilities ? , avr ? , and others are registered trademarks or trademarks of atmel corporation or its subsidiaries. other terms and product names may be trademarks of others.


▲Up To Search▲   

 
Price & Availability of ATMEGA406-14

All Rights Reserved © IC-ON-LINE 2003 - 2022  

[Add Bookmark] [Contact Us] [Link exchange] [Privacy policy]
Mirror Sites :  [www.datasheet.hk]   [www.maxim4u.com]  [www.ic-on-line.cn] [www.ic-on-line.com] [www.ic-on-line.net] [www.alldatasheet.com.cn] [www.gdcy.com]  [www.gdcy.net]


 . . . . .
  We use cookies to deliver the best possible web experience and assist with our advertising efforts. By continuing to use this site, you consent to the use of cookies. For more information on cookies, please take a look at our Privacy Policy. X